Copyright © 1991-1995 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.


Help Files


Documents the SetupWizard application.  For information
about the Setup Toolkit, see the Visual Basic Help file.


Documents Visual Basic for Windows.


Documents the Data Access application.


Documents the Data Manager application.


Tutorials for learning to use Visual Basic for Windows.


Documents Microsoft Support Services.


Lists the applications written in Visual Basic that demonstrate
techniques discussed in the printed documentation.


Documents the custom controls provided with the
Professional Edition.


Documents the Crystal Reports application.


Documents the segmented hypergraphic editor for creating
hotspots within graphics for use in authoring Help files.


Documents the installation tools for ODBC.


Documents the ODBC driver for SQL Server databases.


Documents the VisData sample application.


Documents Windows functions as used in the C programming language.


Documents the Code Profiler add-in.


Documents Remote Automation, the Component Manager,
Remote Data Objects (RDO), and the RemoteData control
provided with the Enterprise Edition.


Documents the SourceSafe add-in for administrators.


Documents the SourceSafe add-in for users.


Text Files

Microsoft Visual Basic 4.0 includes additional information in the following files:

Text File	Description

APILOD.TXT	Describes how to use the API Text Viewer.

LABELS.TXT	Contains information about mailing labels.

PACKING.LST	Lists all files on the distribution disks provided with Visual Basic.

VB4DLL.TXT	Contains additional information about developing dynamic link libraries (DLLs) to use with Visual Basic.

WIN31API.TXT	Contains procedure, constant, and type declarations for 16-bit versions of Windows API functions.

WIN32API.TXT	Contains symbolic constants for 32-bit versions of Windows API functions.

WINMMSYS.TXT	Contains procedure, constant, and type declarations for Windows 3.1 multimedia API functions.


Microsoft Knowledge Base
 Using the Microsoft Knowledge Base

The Microsoft Knowledge Base (KB) is a primary source of product information for Microsoft support engineers and customers. This comprehensive collection of articles contains more than 56,000 detailed how-to articles, answers to technical support questions, bug lists, fix lists, documentation errors, drivers, and sample code.

How to Navigate Within the KB

How to Get Microsoft Knowledge Base Articles

How to Get the Knowledge Base on CD

How to Contribute to the KB


How to Navigate Within the KB

At the top of each KB article, you will find information characterizing the content of the article. This information includes the title of the article, the article Q number, the product name, the version, and operating system. The following shows this information, although not necessarily in the format in which it might appear:

Title: Troubleshooting Insufficient Memory Errors

Document number (unique identifier, Q number): Q112676

Product name or product code: Win3x

Product version: 3.10 3.11

Operating system: Windows

Keywords

All KB articles are categorized and contain keywords describing their content. You can locate articles more effectively by using keywords in your searches.

Note

Some product groups offer their KB articles in Windows Help files. To find out if you can obtain all the KB articles for a specific product in a Help file, search the Microsoft Knowledge Base using the keywords, kbfile and help.


Searching for Any KB Article
Searching for KB Articles Using Keywords

All KB articles are categorized and include keywords to help you find the type of information you are interested in. Below are the keywords and their meanings:

Keyword	Description

kb3rdparty	Interactions with third-party products

kbappnote	Application Notes

kbatwork	Microsoft At Work

kbbuglist	List of all bugs for a particular version of a product

kbcode	Sample code

kbdisplay	Display (video, monitor, resolution) issues

kbdocerr	Documentation errors

kbenv	Environment and configuration

kberrmsg	Error message followup information

kbfasttip	FastTip scripts or maps

kbfile	Binary file information located in the MSL: sample code, drivers, macros

kbfixlist	List of all fixed bugs for a particular version of a product

kbgraphic	Graphics

kbhw	Hardware

kbinterop	Interoperability with other Microsoft products

kbkeyword	Lists of product-specific keywords

kbmacro	Sample macros

kbmm	Multimedia

kbnetwork	Networking

kbole	OLE technology

kbother	Other - any subject not covered in other categories

kbpolicy	Support boundaries, policies, processes, and procedures

kbprb	Problems not classified as bugs

kbprg	Programming

kbprint	Printing

kbreadme	Readme files

kbref	References and lists (phone numbers, directories, etc.)

kbsetup	Setup and installation

kbtlc	FastTip Technical Library Catalog (TLC) items

kbtool	Tools and utilities such as Print Manager or Write

kbtshoot	Troubleshooting information

kbsound	Sound (audio) issues

kbui	User Interface

kbusage	How to use product functionality

New Keywords

New keywords may be added to this list over time. A list of the current keywords is available in the KB in article Q94671, KB Categories and Keywords for All KB Articles. You can use "Q94671" as a keyword to find this article.

Product-Specific Keywords

There may be product-specific keywords for the product you are interested in. To see if there are, search for the name of the product and the kbkeyword keyword in the KB.


How to Contribute to the KB

The Microsoft Knowledge Base staff accepts well-tested technically accurate information for possible inclusion in the KB.

When submitting an article, please ensure that it is fully tested and includes all the following information:

Name of the author(s) or contributor(s)

Name of the person(s) who technically reviewed the information

Product name(s)

Product version number(s)

Operating system(s)

Short summary of the information

Your phone number

On the Internet, please send mail to:

y-kbfeed@microsoft.com

In CompuServe Mail, put the following on the TO: line of your message:

>internet: y-kbfeed@microsoft.com


How to Find Microsoft Knowledge Base Articles
Microsoft Knowledge Base Articles

The best way to get the latest Microsoft product information is by using the Microsoft Knowledge Base. KB articles are updated daily and cover a wide range of information.

KB Articles on the Internet

KB Articles on CompuServe

KB Articles from the Microsoft FastTips Service (Articles by Fax)

KB Articles on CD (Microsoft TechNet and Developer Network)

KB Articles from the Microsoft Download Service (MSDL)

How to Get Microsoft Software Library Files

The product you are researching may have Help files, Application Notes, drivers, or utilities available. If this is the case, you can obtain these from the services above as well.

To find out what Help files are available, you can search the KB for Help files.


Microsoft Knowledge Base Articles on CompuServe

You can obtain KB articles on CompuServe by going to the Microsoft Knowledge Base area. For information about any Microsoft product, including applications, operating systems, hardware, or languages, type

go mskb

at any CompuServe prompt. For development-specific information, type

go mdkb

at any CompuServe prompt.

For additional information, please see the following article in the Microsoft Knowledge Base:

ARTICLE-ID: Q70032

TITLE     : How to Query the Microsoft Knowledge Base on CompuServe

WinCIM

You can also obtain KB articles on CompuServe using WinCIM, the CompuServe Information Manager for Windows. In WinCIM:

1. From the Services menu, choose Go.

2. In the text box, type MSKB.


Microsoft Knowledge Base Articles on MSDL
Microsoft Knowledge Base Articles on Microsoft Download Service (MSDL)

The Microsoft Download Service (MSDL) is a standard bulletin board system (BBS). It contains the Microsoft Software Library (MSL), Application Notes, drivers, Help files, and other support files from Microsoft. MSDL supports 1200, 2400, 9600, and 14,400 baud (V.32 and V.42) with 8 data bits, 1 stop bit, and no parity. The supported protocols are Xmodem, Xmodem-1K, Ymodem (batch), Kermit, Super Kermit (Sliding Windows), and Zmodem.

To connect to MSDL, use your modem to call (206) 936-6735 and then follow the instructions.

See also How to Connect to the MSDL


You can search for KB articles that contain information about Help files available on the Microsoft Software Library by using the kbfile and help keywords.

See also

How to Navigate Within the KB


You can search for KB articles that contain information about files available on the Microsoft Software Library by using the kbfile keyword.

See also

How to Navigate Within the KB


Microsoft Knowledge Base Articles on the Internet

KB articles are available on the Internet through the World Wide Web and through an FTP service (ftp.microsoft.com).

Using the Microsoft World Wide Web Server

Using the Microsoft FTP Server


Using the Microsoft World Wide Web Server

World Wide Web

You can connect to Microsoft's World Wide Web service at http://www.microsoft.com. Choose Knowledge Base from the Microsoft home page and follow the prompts. The home page (or top-level display) on the server also has pointers to ftp.microsoft.com and gopher.microsoft.com, so it makes an ideal entry-point to Internet services at Microsoft.

The Microsoft Knowledge Base on World Wide Web provides full-text searches and hot links to files on the Microsoft Software Library (MSL) so you can download files directly from articles. See How to Find KB Articles on the World Wide Web Server.

Note

HTTP (or HyperText Transfer Protocol) is widely used on the Internet for publishing information with links to other items. It is often referred to as a HyperMedia service because it allows pointers to different media items, such as, text, pictures, sounds, movies.


How to Find KB Articles on the World Wide Web Server

To Find KB Articles on the Web Server

1.	You will need to obtain a World Wide Web client and a SLIP or PPP account from a local Internet Access provider (see World Wide Web Clients, below).

2.	Connect to the Microsoft World-Wide Web server (www.microsoft.com).

3.	Click the Microsoft Knowledge Base option on the menu map, or if you are using a text-only browser, such as Lynx, click the Microsoft Knowledge Base And Software Library option (http:/www.microsoft.com/pages/kb/kb.htm).

4.	Select the Knowledge Base that you would like to search.

5.	On each of the product home pages, you will find a query interface for that product, and a list of keywords that will help in searching the KB. If your query returns successfully, you will see a list of hits. Each of these hits will be a link to an article, and will bring up the article when clicked. If you want to save the text of the article, you can either use the "copy" or the "load to disk" option, which should be available from the main menu of your client software.

World Wide Web Clients

Several public domain HTTP clients are available for many platforms including Microsoft Windows. One of the more popular ones, MOSAIC, is a multi-protocol browser that allows you to access any of the common Internet services from a GUI interface. This means that the client can attach to www.microsoft.com and view the home page, then follow links to information on any of the other servers. Some of the links even point to servers elsewhere on the Internet.

Note

Internet browsing support requires an existing Internet connection via a server (or proxy), or a dialup SLIP/PPP account. Internet connectivity can be obtained from an Internet service provider. Please contact your local computer dealer or vendor for more information on establishing these Internet accounts.

For Assistance

Microsoft cannot provide end user assistance on the use of public domain clients to reach our servers. Please consult your client software documentation or vendor as needed. We welcome suggestions for content, reports of apparent server-end problems, and general comments. Send them to these email addresses:

FTP:    ftp@microsoft.com

Gopher: gopher@microsoft.com

HTTP:   www@microsoft.com


Using the Microsoft FTP Server

FTP

If you don't have access to a World Wide Web provider, you can still connect to Microsoft on the Internet. Connection to the Microsoft Internet Servers requires a "live" session to the Internet through a file transfer program (FTP) service provider.

1.	Log on to your Internet account.

2.	At the Internet prompt, type

open ftp.microsoft.com

3.	When prompted for a user name, type:

anonymous

4.	When asked for a password, type your full electronic mail address (for example, johndoe@test.com).

Note

The server ftp.microsoft.com allows anyone to log on as "anonymous" with their full email name as the password. It uses the FTP server software included with Windows NT. There are banner files and readme files in many of the directories, and a partial directory listing (LS-LR.ZIP) in the root. Be sure to use binary mode (type "bin" to set binary mode) when downloading binary files such as those with .ZIP or .EXE extensions. You must have write permission in your current local working directory, or you will receive "access denied" errors when you try to "get" files. Usage instructions for ftp client software should be provided in the documentation for the ftp software, and your local network administrator may be able to help you.

To find KB articles on the FTP server, see How to Find KB Articles on the FTP Server.


How to Find KB Articles on FTP Server
How to Find KB Articles on the FTP Server

Groups

KB articles are organized by many levels of directories. The first level divides Microsoft products into the following groups:

Advsys	Windows NT, Microsoft Mail, SQL Server, Open Data Base Connectivity (ODBC), and LAN Manager

Deskapps	Desktop applications, including Microsoft Excel, Word for Windows, and Office

Developr	Development tools and languages

Peropsys	Personal operating systems, including Microsoft Windows, Windows for Workgroups, MS-DOS, and Microsoft Mouse

Each group is then divided by product. For example, to access the personal operating system area, change to the PEROPSYS directory by typing the following at the FTP prompt:

cd /peropsys

Products

Each group area contains subdirectories for each product contained in the group area. Under the PEROPSYS directory, the following subdirectories are available:

WINDOWS	Microsoft Windows versions 3.0 and later, Windows for Workgroups, and Windows Multimedia

MSDOS	Microsoft MS-DOS

HARDWARE	Microsoft Mouse

Use the CD command from the FTP prompt to select the subdirectory you are interested in. Each product subdirectory contains a KB subdirectory in which the actual KB articles are stored.

Index of Articles

Once you are in the KB directory, download the README.TXT and INDEX.TXT files. README.TXT contains important information about Knowledge Base articles. INDEX.TXT contains a list of article titles and KB article IDs for each article. You must determine the KB article ID before you can download the article because there is no search mechanism on the FTP server.

To download these files, type the following at the FTP prompt:

get readme.txt

get index.txt

Once you review README.TXT and INDEX.TXT and determine the article ID you are interested in, you are ready to download a Knowledge Base article.


How to Download a KB Article from the FTP Server Using GET

See also: How to Find KB Articles on the FTP Server

KB articles are stored in a tree structure. Each KB article ID is translated into a two-digit filename and stored two subdirectories under the KB directory. This method helps organize articles more effectively and improves server performance.

You do not need to change to the directory that contains the KB article you want to download. The directory structure is consistent for all major categories. You can use the GET command to obtain an article from the <product>/kb directory.

How to Download a KB Article

The following steps show you how to download a KB article about Windows for Workgroups, How to Troubleshoot WFWG Network Connection Problems. You can find the KB article ID, Q104322, in the INDEX.TXT file.

1.	After logging on to the FTP server, change to the PEROPSYS directory:

cd /peropsys

2.	Change to the WINDOWS directory:

cd windows

3.	Change to the KB directory:

cd kb

4.	Translate the article ID into a GET command. There are three parts of the KB article ID to be divided before using the GET command. The filename of the KB article is the last two digits of the ID plus the .TXT extension (22.TXT). The subarea is the third digit from the right of the ID (3). The primary area is the remaining three characters to the left (or the remaining two characters in the case of a five-digit Q number), plus the "Q". To use the GET command, place a slash mark (/) between the primary area, subarea, and filename (primary/sub/filename).

For Q104322, the filename translates to:

Q104322 = Q104/3/22.TXT

5.	Use the GET command at the FTP prompt to transfer the article to your system as follows:

get q104/3/22.txt q104322.txt

The "Q104322.TXT" part of the command above is the destination name for the file. The destination name is the name of the file as it appears on your hard disk drive.

Be sure to use binary mode (type "bin" to set binary mode) when downloading binary files such as those with .ZIP or .EXE extensions.

6.	To close the connection with the server for most FTP clients, type the following from the FTP prompt:

bye


The INDEX.TXT file contains a list of all the KB articles available in the current area. To get this file, you need to know how to find KB articles.


How to Get the KB on CD
How to Get the Knowledge Base on CD

You can get the KB on CD by subscribing to two different services, the Microsoft Developer Network (MSDN) and Microsoft TechNet. Both of these services offer the Microsoft KB and complete Microsoft Software Library (MSL), as well as many other information resources.

Microsoft Developer Network (MSDN)

Microsoft TechNet


Microsoft TechNet

Microsoft TechNet is a CD-ROM-based information subscription service created for those who support or educate end users, administer networks or databases, create automated solutions, and recommend or evaluate information technology solutions. Microsoft TechNet is the front-line resource for fast, complete answers to technical questions on Microsoft desktop and systems products.

Microsoft TechNet Benefits Include the Following

Twelve monthly Microsoft TechNet CDs, containing the complete Microsoft Knowledge Base, complete product Resource Kits, customer solutions, session notes from key Microsoft conferences, and other valuable technical and strategic information.

Twelve monthly Microsoft TechNet Supplemental (drivers and patches) CDs, containing the complete Microsoft Software Library (includes drivers for the entire line of Microsoft software products, code samples, articles and useful utilities) and patches for many Microsoft products, including the Microsoft Windows NT operating system.

A dedicated Microsoft TechNet CompuServe forum (GO TECHNET).

WinCIM, a Windows-based application for accessing CompuServe.

$20 credit on CompuServe connect charges for first-time Microsoft TechNet members.

A 20% discount on Microsoft Press books.

To Join the Microsoft TechNet

In the U.S. and Canada, call (800) 344 2121, dept. 3021; 6:30 AM to 5:30 PM (Pacific Time), Monday-Friday

In France, call 05 90 59 04 (Toll Free)

In Germany, call 0130 8102 11 (Toll Free)

In the Netherlands, call 06 022 24 80 (Toll Free)

In the United Kingdom, call 0800 96 02 79 (Toll Free)

All other European Countries, call +31 10 258 88 64

In Australia, call 612 870 2100

In Argentina, call 54 1 814 5105

In Brazil, call (55) 11 725 3711

In the Caribbean Region, call 1 (800) 344 2121, or 1 (800) 759 5474, or 402 691 0173; dept. 3021; 6:30 AM to 5:30 PM (Pacific Time), Monday-Friday

In Chile, call 56 2 204 8257

In Colombia, call (57) (1) 618 2245

In Hong Kong, call (852) 2756 5560

In India, call 91 11 646 0694

In Israel, call (972) (3) 575 7034

In Japan, call 81 3 5600 5036

In Mexico, call 52 5 325 0911

In New Zealand, call 64 9 308 9318

In Russia, call 7 095 244 3474

In Singapore, call (65) 738 7300

In South Africa, call 27 11 445 0000

In South Korea, call 82 2 531 4500

In Taiwan, call (886) (2) 504 3122

In Turkey, call 90 212 258 59 98

In United Arab Emirates, call 971 4 513888

In Venezuela, call 58 2 993 1929

Note

This information is current as of March, 1995. This information is subject to change.


Microsoft Developer Network (MSDN)

The Microsoft Developer Network (MSDN) provides technical information and development toolkits for all developers who write applications for Microsoft operating systems. MSDN members receive a quarterly CD-ROM disk and a bimonthly newsletter. The CD contains code samples, technical articles, development tools, and the Microsoft Knowledge Base.

To Join the MSDN

In the U.S. and Canada, call (800) 759-5474; Dept. 1001; This number is available 24 hours a day, 7 days a week.

In France, call 05 90 59 04 (toll-free).

In Germany, call 0130 81 02 11.

In the Netherlands, call 06 022 24 80 (toll-free).

In the United Kingdom, call 0800 96 02 79 (toll-free).

In Japan, call 03 5461 5033.

For any other country in Europe, call +31 10 258 88 64.

Outside Europe, the U.S., Canada, or Japan, call (303) 684 0914.

Note

This information is current as of March, 1995. This information is subject to change.


KB Articles from the Microsoft FastTips Service
KB Articles from the Microsoft FastTips Service (Articles by Fax)

Microsoft FastTips is available 24 hours a day, 7 days a week, from a touch-tone telephone. To obtain a list of the articles available from Microsoft FastTips, call one of the numbers in Step 1, below. Follow the prompts to order the catalog and map. The map outlines the structure of Microsoft FastTips and makes it easier to find what you need quickly. The catalog contains all the available articles and Application Notes.

To order items from the FastTips catalog, first select the items you want to receive by noting the four- to six-digit number (in bold) of the Item ID shown below each item, and then:

1.	Dial one of the toll-free FastTips numbers:

Desktop applications	(800) 936-4100

Personal operating systems	(800) 936-4200

Development tools	(800) 936-4300

Business systems	(800) 936-4400

2.	When prompted, select the Microsoft product you are calling about.

3.	Press 1 on your phone keypad to select Express Order Service.

4.	When prompted, select fax as your preferred delivery method.

5.	When prompted, enter the number of the Item ID and then press #. You can select up to five items.

6.	When prompted, enter your three-digit area code and seven-digit fax number on your phone keypad.

Note

The Microsoft FastTips service is available only in the U.S.


Microsoft Software Library (MSL)

The MSL contains files, including drivers, utilities, Help files, and Application Notes, for all Microsoft products. To find out what files are available for the product you are interested in, you can search the KB for MSL files.

Internet

You can obtain MSL files from the Internet by going to the SOFTLIB\MSLFILES directory.

Microsoft Download Service

The MSL is also available on the Microsoft Download Service (MSDL), Microsoft's own bulletin board system (BBS).

CompuServe

To go to the MSL on CompuServe, type

go msl

at any CompuServe prompt.

WinCIM

You can also obtain KB articles on CompuServe using WinCIM, the CompuServe Information Manager for Windows. In WinCIM:

1. From the Services menu, choose Go.

2. In the text box, type MSL.

CD

The MSL is included in the Microsoft TechNet and Microsoft Developer Network (MSDN) CDs.


How to Connect to the MSDL

The MSDL supports 1200, 2400, 9600, and 14,400 baud rates (V.32 and V.42), with 8 data bits, 1 stop bit, and no parity. After you have chosen these settings, you can begin the session as follows:

1.	Call the MSDL at (206) 936-6735.

2.	Enter your full name and the location you are calling from.

The MSDL will list some basic instructions and information.

If you have a 9600 or 14.4 bps modem and are connecting at a lower speed, then disable V.32bis and V.42bis on your modem and try reconnecting.


Glossary


Glossary

See Also

A

access key

action query

action QueryDef

active window

add-in

aggregate function

alias

ANSI Character Set

append query

application

argument

array

ASCII Character Set

assignment statement

asterisk

attached table

automatic formatting

B

base table

binary format

bit

bit-wise comparison

bitmap

bitmask

bookmark

Boolean

Boolean expression

bound control

break mode

breakpoint

by reference

by value

Byte data type

C

Calls button

Cancel button

Cartesian product

cascade

cascade delete

cascade update

cascading event

case-sensitive

character code

check box

class

class module

Clipboard

code module

collection

collection syntax

column

command line

comment

commit

comparison operator

compile error

compile time

compound document file

conditional compiler constant

connect string

consistent

constant

container

control

control array

Control Panel

Control-menu box

Control-menu commands

controlling application

copy buffer

counter

counter field

criteria

cross hair

crosstab query

Currency data type

current database

current index

current record

current transaction

custom control

D

data access object

Data control

data page

data source

data type (Data Access)

data type

data type ranges

data-definition query

database

database administration

database engine

database management system (DBMS)

Database object

database objects

date expression

date literal

date separators

dates and times

DDL (Data Definition Language)

declaration

default color box

default workspace

delete query

design time

destination

device context

dialog box

domain

domain aggregate function

Double data type

drag-and-drop operation

dynamic data exchange (DDE)

dynamic-link library (DLL)

dynaset

Dynaset object

E

EB data type

editing key

embedded object

Empty

equi-join

error number

error trapping

event

event procedure

exclusive

executable file

expression (Data Access)

expression

external database

external table

F

field

field data types

field properties

file number

filter

flag

focus

foreign key

foreign table

form

form module

forward scroll

forward-only scrolling snapshot

FROM clause

function key

Function procedure

G

general procedure

graphics method

group

H

handle

host application

I

icon

identifier

Immediate pane

in-place activation

inconsistent

index (Data Access)

index

initialization file

inner join

insertable object

insertion point

installable ISAM

instance

Integer data type

internal area

intrinsic constant

J

join

K

keyword

L

left join

left outer join

line label

line number

line-continuation character

linked object

list box

locale

locked

logic error

Long Binary

Long data type

M

make table query

many-only table

master copy

Maximize button

MDI child

MDI form

member

Memo data type

Memo object

memory object

message

metafile

method

Microsoft Jet database engine

Minimize button

modal

modeless

module

module level

module variable

multiuser database

N

named argument

normalize

null (Data Access)

Null

null field

Null propagation

numeric expression

numeric type

O

object

OLE server

Object box

Object Browser

object data type

object expression

object library

object type

object variable

ODBC (Open Database Connectivity)

ODBC data source

ODBC driver

OLE

OLE Automation

OLE Automation controller

OLE Automation object

OLE custom control

OLE Object data type

OLE server

one-to-many relationship

one-to-one relationship

optimistic

option button

outer join

P

page

parameter (Data Access)

parameter

parameter query

parent form

parse

pass-through query

Paste Link command

path

pen

permission

persistent graphic

persistent object

personal identifier (PID)

pessimistic

pi

pixel

point

poke

pop-up menu

position indicator

primary key

primary table

print zone

procedure

Procedure box

procedure call

procedure level

procedure template

project

project file

Project window

Properties button

Properties window

property

Property list

Property procedure

Q

query

query parameter data types

QueryDef object

R

read-only

read-only file

record

recordset

recordset population

recursion

referential integrity

registry

requery

reserved word

resource file

right join

right outer join

row

run time

run-time error

S

SCODE

scope

secure workgroup

security

seed

select query

self-join

separator bar

server

session

shadowing

shortcut key

Single data type

size indicator

snapshot

Snapshot object

sort order

source

split bar

SQL database

SQL statement/string

SQL-specific query

stack

standard control

standard deviation

standard module

standard naming conventions

startup form

statement

Static

string comparison

string constant

String data type

string expression

string literal

string type

Structured Query Language (SQL)

Sub procedure

submenu

syntax

syntax checking

syntax error

system modal

system object

T

tab order

table

Table object

TableDef object

TEMP

temporary disk

Text data type

time expression

title bar

transaction

twip

two's complement

type library

type-declaration character

U

Unicode

union query

universal date format

update

update query

user account

user-defined type

user-interface negotiation

V

validation

validation properties

validation rule

variable

Variant data type

variant expression

VarType

verb

visual editing

W

watch expression

Watch pane

WHERE clause

wildcard characters

Windows API

Windows OpenFile function

workgroup

workgroup administrator

working directory

workspace

Y

Yes/No data type

Z

z-order

zero-length string


See Also

Visual Basic Help


Application <keyword>
Application

The Application keyword is used in these contexts:

Application Object (Add-In)

Application Property (Add-In)


ControlTemplates <keyword>
ControlTemplates

The ControlTemplates keyword is used in these contexts:

ControlTemplates Collection (Add-In)

ControlTemplates Property (Add-In)


FileControl <keyword>
FileControl

The FileControl keyword is used in these contexts:

FileControl Object (Add-In)

FileControl Property (Add-In)


Flags <keyword>
Flags

The Flags keyword is used in these contexts:

Flags Property (Color Dialog)

Flags Property (File Dialog)

Flags Property (Font Dialog)

Flags Property (Print Dialog)


Image <keyword>
Image

The Image keyword is used in these contexts:

Image Control

Image Property


Line

The Line keyword is used in these contexts:

Line Method

Line Input # Statement

Line Control


LinkExecute <keyword>
LinkExecute

The LinkExecute keyword is used in these contexts:

LinkExecute Event

LinkExecute Method


Load <keyword>
Load

The Load keyword is used in these contexts:

Load Event

Load Statement


MenuItems <keyword>
MenuItems

The MenuItems keyword is used in these contexts:

MenuItems Collection (Add-In)

MenuItems Property (Add-In)


Properties <keyword>
Properties

The Properties keyword is used in these contexts:

Properties Collection (Add-In)

Properties Property (Add-In)


Refresh

Refresh Method

Refresh Method (Data Access)


SelectedComponents <keyword>
SelectedComponents

The SelectedComponents keyword is used in these contexts:

SelectedComponents Collection (Add-In)

SelectedComponents Property (Add-In)


Shape <keyword>
Shape

The Shape keyword is used in these contexts:

Shape Control

Shape Property


Timer <keyword>
Timer

The Timer keyword is used in these contexts:

Timer Control

Timer Event


Unload <keyword>
Unload

The Unload keyword is used in these contexts:

Unload Event

Unload Statement


SELECT

The SELECT keyword is used in these contexts:

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)


In

The In keyword is used in these contexts:

In Operator (SQL)

IN Clause (SQL)


Object

The Object keyword is used in these contexts:

Object Property

Object Property (OLE Container)


Event Summary


Event Summary

See Also

A

Activate

AfterAddFile (Add-In)

AfterChangeFileName (Add-In)

AfterCloseFile (Add-In)

AfterColUpdate

AfterDelete

AfterInsert

AfterNewProject (Add-In)

AfterRemoveFile (Add-In)

AfterUpdate

AfterWriteFile (Add-In)

B

BeforeColUpdate

BeforeDelete

BeforeInsert

BeforeLoadFile (Add-In)

BeforeUpdate

C

Change

CheckIn (Add-In)

CheckOut (Add-In)

Click

ColResize

ConnectAddIn (Add-In)

D

DblClick

Deactivate

DisconnectAddIn (Add-In)

DoGetAddFileName (Add-In)

DoGetNewFileName (Add-In)

DoGetOpenProjectName (Add-In)

DragDrop

DragOver

DropDown

E

Error

F

Fetch (Add-In)

G

GotFocus

H

HeadClick

I

Initialize

K

KeyDown

KeyPress

KeyUp

L

LinkClose

LinkError

LinkExecute

LinkNotify

LinkOpen

Load

LostFocus

M

MouseDown

MouseMove

MouseUp

O

ObjectMove

P

Paint

PathChange

PatternChange

Q

QueryUnload

R

Reposition

RequestChangeFileName (Add-In)

RequestWriteFile (Add-In)

Resize

RowColChange

RowLoaded

RowResize

S

Scroll

SelChange

T

Terminate

Timer

U

UnboundAddData

UnboundDeleteRow

UnboundReadData

UnboundWriteData

UnCheckOut (Add-In)

Unload

Updated

V

Validate


See Also

Data Access Events

Functions

Keywords by Task

Methods

Objects

Programming Language Summary

Properties

Statements

Visual Basic Help


Function Summary


Function Summary

See Also

A

Abs

Array

Asc

AscB

Atn

C

CBool

CByte

CCur

CDate

CDbl

Choose

Chr

ChrB

CInt

CLng

Command

Cos

CreateDatabase

CreateObject

CSng

CStr

CurDir

CVar

CVErr

D

Date

DateAdd

DateDiff

DatePart

DateSerial

DateValue

Day

DDB

Dir

DoEvents

E

Environ

EOF

Error

Exp

F

FileAttr

FileDateTime

FileLen

Fix

Format

FreeFile

FV

G

GetAllSettings

GetAttr

GetObject

GetSetting

H

Hex

Hour

I

IIf

IMEStatus

Input

InStr

Int

IPmt

IRR

IsArray

IsDate

IsEmpty

IsError

IsMissing

IsNull

IsNumeric

IsObject

L

LBound

LCase

Left

Len

LoadPicture

LoadResData

LoadResPicture

LoadResString

Loc

LOF

Log

LTrim

M

Mid

Minute

MIRR

Month

MsgBox

N

Now

NPer

NPV

O

Oct

OpenDatabase

P

Partition

Pmt

PPmt

PV

Q

QBColor

R

Rate

ReadProperty

RGB

Right

Rnd

RTrim

S

Second

Seek

Sgn

Shell

Sin

SLN

Space

Spc

Sqr

Str

StrComp

StrConv

String

Switch

SYD

T

Tab

Tan

Time

Timer

TimeSerial

TimeValue

Trim

TypeName

U

UBound

UCase

V

Val

VarType

W

Weekday

Y

Year


See Also

Events

Keywords by Task

Methods

Objects

Programming Language Summary

Properties

Statements

Visual Basic Help


Programming Language Summary


Programming Language Summary

See Also

A

Activate Event

ActiveControl Property

ActiveForm Property

ActiveProject Property (Add-In)

Add Method

Add Method (Add-In)

Add Method (DBGrid)

AddFile Method (Add-In)

AddFormTemplate Method (Add-In)

AddInMenu Property (Add-In)

AddItem Method

AddMDIFormTemplate Method (Add-In)

AddMenu Method (Add-In)

AddMenuTemplate Method (Add-In)

AddNew Method

AddReference Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxTypelib Method (Add-In)

AddToolboxVBX Method (Add-In)

AfterAddFile Event (Add-In)

AfterChangeFileName Event (Add-In)

AfterCloseFile Event (Add-In)

AfterColUpdate Event

AfterDelete Event

AfterInsert Event

AfterNewProject Event (Add-In)

AfterRemoveFile Event (Add-In)

AfterUpdate Event

AfterWriteFile Event (Add-In)

Aggregate Functions for SQL Only

Aggregate Functions, Domain (SQL)

Align Property

Alignment Property

AllowAddNew Property

AllowDelete Property

AllowRowSizing Property

AllowSizing Property

AllowUpdate Property

AllowZeroLength Property

AllPermissions Property

And Operator

App Object

AppActivate Statement

Appearance Property

Append Method

AppendChunk Method

AppIsRunning Property

Application Object (Add-In)

Application Property (Add-In)

Archive Property

Arrange Method

Array Function

Asc Function

AscB

As

Atn Function

Attributes Property

AutoActivate Property

AutoRedraw Property

AutoShowChildren Property

AutoSize Property

AutoVerbMenu Property

B

BackColor Property

BackStyle Property

Beep Statement

BeforeColUpdate Event

BeforeDelete Event

BeforeInsert Event

BeforeLoadFile Event (Add-In)

BeforeUpdate Event

BeginTrans Statement

BOF Property

BOFAction Property

Bold Property

Bookmark Property (Data Access)

Bookmark Property (DBGrid)

Bookmarkable Property

BorderColor Property

BorderStyle Property

BorderWidth Property

BoundColumn Property

BoundText Property

ByVal

C

CacheSize Property

CacheStart Property

Call Statement

Cancel Property

CancelError Property

CancelUpdate Method

Caption Property

CBool Function

CByte Function

CCur Function

CDate Function

CDbl Function

CellSelected Property

CellText Method

CellValue Method

Change Event

Character Set

ChDir Statement

ChDrive Statement

Checked Property

CheckIn Event (Add-In)

CheckOut Event (Add-In)

Choose Function

Chr Function

ChrB

CInt Function

Circle Method

Class Property

ClassModule Object

ClassName Property (Add-In)

Clear Method (Clipboard, ComboBox, ListBox)

Clear Method

Click Event

Clip Property

Clipboard Object

ClipControls Property

CLng Function

Clone Method

Close Method (OLE Container)

Close Method

Close Statement

Cls Method

Clustered Property

Col Property

ColAlignment Property

ColContaining Method

ColIndex Property

ColIsVisible Property

CollatingOrder Property

Collection Object

Color Property

ColorMode Property

ColPos Property

ColResize Event

Cols Property

Column Object

ColumnCount Property

ColumnHeaders Property

ColumnName Property

Columns Collection

Columns Property (DBGrid)

Columns Property (ListBox)

ColWidth Property

Command Function

Command Line Switches

CommandButton Control

Comments Property

CommitTrans Statement

CommonDialog Control

CompactDatabase Method

CompactDatabase Statement

CompanyName Property

Component Object (Add-In)

Components Collection (Add-In)

ConflictTable Property

Connect Property

ConnectAddIn Event (Add-In)

ConnectEvents Method (Add-In)

Const Statement

Container Object

Container Property (Add-In)

Container Property (Data Access)

Container Property

Containers Collection

ControlBox Property

Controls Collection

ControlTemplate Object (Add-In)

ControlTemplates Collection (Add-In)

ControlTemplates Property (Add-In)

Copies Property

Copy Method

CopyQueryDef Method

Cos Function

Count Property (Data Access)

Count Property (VB Collections)

CreateDatabase Function

CreateDatabase Method

CreateDynaset Method

CreateEmbed Method

CreateField Method

CreateGroup Method

CreateLink Method

CreateObject Function

CreateProperty Method

CreateQueryDef Method

CreateRelation Method

CreateSnapshot Method

CreateTableDef Method

CreateUser Method

CreateWorkspace Method

CSng Function

CStr Function

CurDir Function

Currency Data Type

CurrentX Property

CurrentY Property

CVar Function

CVErr Function

D

Data Control

Data Property

Data Types

Database Object

Database Property

DatabaseName Property

Databases Collection

DataChanged Property

DataField Property

DataMode Property

DataSource Property

DataText Property

DataUpdatable Property

Date Function

Date Statement

DateAdd Function

DateCreated Property

DateDiff Function

DatePart Function

DateSerial Function

DateValue Function

Day Function

DBCombo Control

DBEngine Object

DBGrid Control

DblClick Event

DBList Control

DDB Function

Deactivate Event

Debug Object

Declare Statement

Default Property

DefaultExt Property

DefaultPassword Property

DefaultUser Property

DefaultValue Property

DefColWidth Property

Deftype Statements

Delete Method (OLE Container)

Delete Method

DeleteQueryDef Method

DeleteSetting Statement

Description Property (ClassModule)

Description Property (Data Access)

Description Property

DesignMasterID Property

DeviceName Property

DialogTitle Property

Dim Statement

Dir Function

DisconnectAddIn Event (Add-In)

DisconnectEvents Method (Add-In)

DisplayType Property

DistinctCount Property

DividerStyle Property

Do...Loop Statement

DoEvents Function

DoGetAddFileName Event (Add-In)

DoGetNewFileName Event (Add-In)

DoGetOpenProjectName Event (Add-In)

Domain Aggregate Functions (SQL)

Double Data Type

DoVerb Method

Drag Method

DragDrop Event

DragIcon Property

DragMode Property

DragOver Event

DrawMode Property

DrawStyle Property

DrawWidth Property

Drive Property

DriverName Property

DropDown Event

Duplex Property

Dynaset Object

E

Edit Method

EditMode Property

Else

Enabled Property

End Statement

EndDoc Method

Environ Function

EOF Function

EOF Property

EOFAction Property

Equivalent ANSI SQL Data Types

Erase Statement

Err Object

Error Event

Error Function

Error Object

Error Statement

Errors Collection

Errors, Trappable Data Access

Errors, Trappable

Exclusive Property

Execute Method

ExecuteSQL Method

EXEName Property

Exit Statement

Exp Function

F

False

Fetch Event (Add-In)

FetchVerbs Method

Field Object

Fields Collection

Fields Property

FieldSize Method

FileAttr Function

FileControl Object (Add-In)

FileControl Property (Add-In)

FileCopy Statement

FileCount Property (Add-In)

FileDateTime Function

FileDescription Property

FileLen Function

FileName Property

FileNames Property (Add-In)

FileNumber Property

FileTitle Property

FillCache Method

FillColor Property

FillStyle Property

Filter Property (CommonDialog)

Filter Property

FilterIndex Property

FindFirst Method

FindLast Method

FindNext Method

FindPrevious Method

FirstRow Property

Fix Function

FixedAlignment Property

FixedCols Property

FixedRows Property

Flags Property (Color Dialog)

Flags Property (File Dialog)

Flags Property (Font Dialog)

Flags Property (Print Dialog)

Font Object

Font Property

FontBold Property

FontCount Property

FontItalic Property

FontName Property

Fonts Property

FontSize Property

FontStrikethru Property

FontTransparent Property

FontUnderline Property

For Each...Next Statement

For...Next Statement

ForeColor Property

Foreign Property

ForeignName Property

ForeignTable Property

Form Object

Format Function

Format Property

Forms Collection

FormTemplate Object (Add-In)

Frame Control

FreeFile Function

FreeLocks Statement

FromPage Property

FullName Property (Add-In)

Function Statement

FV Function

G

Get Statement

GetAllSettings Function

GetAttr Function

GetBookmark Method

GetChunk Method

GetData Method

GetFormat Method

GetObject Function

GetRows Method

GetSetting Function

GetText Method

GoSub...Return Statement

GotFocus Event

GoTo Statement

Grid Control

GridLines Property

GridLineWidth Property

Group Object

Groups Collection

H

Handle Property

hDC Property

HeadBackColor Property

HeadClick Event

HeadFont Property

HeadForeColor Property

HeadLines Property

Height Property

HelpCommand Property

HelpContext Property (CommonDialog)

HelpContext Property (Data Access)

HelpContext Property

HelpContextID Property

HelpFile Property (App, CommonDialog, MenuLine)

HelpFile Property (Data Access)

HelpFile Property

HelpKey Property

Hex Function

Hidden Property

Hide Method

HideSelection Property

HighLight Property

hInstance Property

HostName Property

Hour Function

hPal Property

HScrollBar Control

hWnd Property

I

Icon Property

IconState Property (Add-In)

Idle Method

If...Then...Else Statement

IgnoreNulls Property

IIf Function

Image Control

Image Property

IMEStatus Function

Index Property (Control Array)

Index Property (Data Access)

IndexedValue Property (Add-In)

Inherit Property

Inherited Property (Data Access)

IniPath Property

InitDir Property

Initialize Event

Input # Statement

Input Function

InsertFile Method (Add-In)

InsertObjDlg Method

Instancing Property

InStr Function

Int Function

Integer Data Type

IntegralHeight Property

Interval Property

IPmt Function

IRR Function

Is Operator

IsArray Function

IsDate Function

IsDirty Property (Add-In)

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

IsolateODBCTrans Property

Is

Italic Property

Item Method (Add-In)

Item Method

ItemData Property

K

KeepLocal Property

KeyDown Event

KeyPress Event

KeyPreview Property

KeyUp Event

Kill Statement

KillDoc Method

L

Label Control

LargeChange Property

LastDLLError Property

LastModified Property

LastUpdated Property

LastUsedPath Property (Add-In)

LBound Function

LBound Property

LCase Function

Left Function

Left Property

LeftCol Property

LegalCopyright Property

LegalTrademarks Property

Len Function

Let Statement

Like Operator

Line Control

Line Input # Statement

Line Method

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

List Property

ListCount Property

ListField Property

ListFields Method

ListIndex Property

ListIndexes Method

ListParameters Method

ListTables Method

Load Event

Load Statement

LoadPicture Function

LoadProject Method (Add-In)

LoadResData Function

LoadResPicture Function

LoadResString Function

Loc Function

Lock Statement

Locked Property

LockEdits Property

LOF Function

Log Function

LoginTimeout Property

LogMessages Property

Long Data Type

LostFocus Event

lpOleObject Property

LSet Statement

LTrim Function

M

Major Property

MakeReplica Method

MatchedWithList Property

MatchEntry Property

Max Property (CommonDialog)

Max Property (Scroll Bar)

MaxButton Property

MaxFileSize Property

MaxLength Property

MDIChild Property

MDIForm Object

Menu Control

MenuItems Collection (Add-In)

MenuItems Property (Add-In)

MenuLine Object (Add-In)

Me

Microsoft Jet Database Engine SQL Reserved Words

Mid Function

Mid Statement

Min Property (CommonDialog)

Min Property (Scroll Bar)

MinButton Property

Minor Property

Minute Function

MIRR Function

MiscFlags Property

MkDir Statement

Month Function

MouseDown Event

MouseIcon Property

MouseMove Event

MousePointer Property

MouseUp Event

Move Method (Data Access)

Move Method

MoveFirst Method

MoveLast Method

MoveNext Method

MovePrevious Method

MsgBox Function

MultiLine Property

MultiSelect Property

N

Name Property

Name Statement

Negotiate Property

NegotiateMenus Property

NegotiatePosition Property

NegotiateToolbars Property

NewEnum Property (Add-In)

NewIndex Property

NewPage Method

NewPassword Method

New

Next

NoMatch Property

Normal Property

Now Function

NPer Function

NPV Function

Number Property (Data Access)

Number Property

NumberFormat Property

NumIndices Property (Add-In)

O

Object Property (OLE Container)

Object Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property

ObjectMove Event

ObjectVerbFlags Property

ObjectVerbs Property

ObjectVerbsCount Property

Oct Function

ODBCTimeout Property

OLE Container Control

OLEDropAllowed Property

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgText Property

OLEServerBusyMsgTitle Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property

OLEType Property

OLETypeAllowed Property

On Error Statement

On...GoSub Statement

On...GoTo Statement

On

Open Statement

OpenDatabase Function

OpenDatabase Method

OpenQueryDef Method

OpenRecordset Method

OpenTable Method

Operator Summary

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement

OptionButton Control

Options Property

Option

OrdinalPosition Property

Orientation Property

Owner Property

P

Page Property

Paint Event

PaintPicture Method

PaperBin Property

PaperSize Property

Parameter Object

Parameters Collection

Parent Property

Partition Function

Password Property

PasswordChar Property

Paste Method

PasteOK Property

PasteSpecialDlg Method

Path Property

PathChange Event

Pattern Property

PatternChange Event

PercentPosition Property

Permissions Property

Picture Object

Picture Property

PID Property

Pmt Function

Point Method

PopupMenu Method

Port Property

PPmt Function

PrevInstance Property

Primary Property

Print # Statement

Print Method

Printer Object

PrinterDefault Property

Printers Collection

PrintForm Method

PrintQuality Property

Private Statement

ProductName Property

ProjectTemplate Object (Add-In)

Properties Collection (Add-In)

Properties Collection (Data Access)

Properties Property (Add-In)

Property Get Statement

Property Let Statement

Property Object (Add-In)

Property Object (Data Access)

Property Set Statement

PSet Method

Public Property

Public Statement

Put Statement

PV Function

Q

QBColor Function

QueryDef Object

QueryDefs Collection

QueryTimeout Property

QueryUnload Event

R

Raise Method

Randomize Statement

Rate Function

ReadFromFile Method

ReadOnly Property (Data Access)

ReadOnly Property

ReadOnlyMode Property (Add-In)

ReadProperty Function

Rebind Method

RecordCount Property

RecordsAffected Property

RecordSelectors Property

Recordset Object

Recordset Property

Recordsets Collection

RecordsetType Property

RecordSource Property

ReDim Statement

Refill Method

Refresh Method (Data Access)

Refresh Method

RefreshLink Method

RegisterDatabase Method

RegisterDatabase Statement

Relation Object

Relations Collection

Reload Method (Add-In)

Rem Statement

Remove Method (Add-In)

Remove Method (Data Access)

Remove Method

RemoveComponent Method (Add-In)

RemoveItem Method

RepairDatabase Method

RepairDatabase Statement

Replicable Property

ReplicaID Property

Reposition Event

Requery Method

RequestChangeFileName Event (Add-In)

RequestWriteFile Event (Add-In)

Required Property

Reset Statement

Resize Event

Restartable Property

Resume Statement

ReturnsRecords Property

Revision Property

RGB Function

Right Function

RmDir Statement

Rnd Function

Rollback Statement

Row Property

RowBookmark Method

RowBuffer Object

RowColChange Event

RowContaining Method

RowCount Property (DBGrid)

RowDividerStyle Property

RowHeight Property

RowIsVisible Property

RowLoaded Event

RowPos Property

RowResize Event

Rows Property

RowSource Property

RowTop Method

RSet Statement

RTrim Function

S

SaveAs Method (Add-In)

SavePicture Statement

SaveSetting Statement

SaveToFile Method

SaveToOle1File Method

Scale Method

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleTop Property

ScaleWidth Property

ScaleX Method

ScaleY Method

Screen Object

Scroll Event

Scroll Method

ScrollBars Property

Second Function

Seek Function

Seek Method

Seek Statement

SelBookmarks Collection

SelBookmarks Property

SelChange Event

SelCount Property

Select Case Statement

Selected Property

SelectedComponents Collection (Add-In)

SelectedComponents Property (Add-In)

SelectedControlTemplates Collection (Add-In)

SelectedControlTemplates Property (Add-In)

SelectedItem Property

SelEndCol Property

SelEndRow Property

SelLength Property

SelStart Property

SelStartCol Property

SelStartRow Property

SelText Property

SendKeys Statement

Set Statement

SetAttr Statement

SetData Method

SetDataAccessOption Statement

SetDefaultWorkspace Statement

SetFocus Method

SetText Method

Sgn Function

Shape Control

Shape Property

Shell Function

Shortcut Property

Show Method

ShowColor Method

ShowFont Method

ShowHelp Method

ShowInTaskbar Property

ShowOpen Method

ShowPrinter Method

ShowSave Method

ShowWhatsThis Method

Sin Function

Single Data Type

Size Property (Data Access)

Size Property (Font)

SizeMode Property

SLN Function

SmallChange Property

Snapshot Object

Sort Property

Sorted Property

Source Property (Data Access)

Source Property

SourceDoc Property

SourceField Property

SourceItem Property

SourceTable Property

SourceTableName Property

Space Function

Spc Function

SQL Property

Sqr Function

StartMode Property

Static Statement

Stop Statement

Str Function

StrComp Function

StrConv Function

Stretch Property

StrikeThrough Property

String Data Type

String Function

Style Property

Sub Statement

SubMenu Object (Add-In)

Switch Function

SYD Function

Synchronize Method

System Property

T

Tab Function

TabIndex Property

Table Object

Table Property

TableDef Object

TableDefs Collection

TabStop Property

Tag Property

Tan Function

TaskVisible Property

Terminate Event

Text Property

TextHeight Method

TextWidth Method

Time Function

Time Statement

Timer Control

Timer Event

Timer Function

TimeSerial Function

TimeValue Function

Title Property

Top Property

ToPage Property

TopIndex Property

TopRow Property

To

TrackDefault Property

Transactions Property

Trim Function

True

TwipsPerPixelX Property

TwipsPerPixelY Property

Type Property (Data Access)

Type Property (Picture)

Type Statement

TypeName Function

U

UBound Function

UBound Property

UCase Function

UnboundAddData Event

UnboundDeleteRow Event

UnboundReadData Event

UnboundWriteData Event

UnCheckOut Event (Add-In)

Underline Property

Unique Property

Unload Event

Unload Statement

Unlock Statement

Updatable Property

Update Method (Data Access)

Update Method (OLE Container)

UpdateControls Method

Updated Event

UpdateOptions Property

UpdateRecord Method

UseMnemonic Property

User Object

User-Defined Data Type

UserName Property

Users Collection

V

V1xNullBehavior Property

Val Function

Validate Event

ValidateOnSet Property

ValidationRule Property

ValidationText Property

Value Property (Add-In)

Value Property (Data Access)

Value Property (RowBuffer)

Value Property

VarType Function

Verb Phroperty

Version Property (Add-In)

Version Property

Visible Property

VisibleCols Property

VisibleCount Property

VisibleItems Property

VisibleRows Property

VScrollBar Control

W

Weekday Function

Weight Property

WhatsThisButton Property

WhatsThisHelp Property

WhatsThisHelpID Property

WhatsThisMode Method

While...Wend Statement

Width # Statement

Width Property

WindowList Property

WindowState Property

With Statement

WordWrap Property

Workspace Object

Workspaces Collection

Write # Statement

WriteProperty Method (Add-In)

X

X1 Property

X2 Property

Y

Y1 Property

Y2 Property

Year Function

Z

Zoom Property

ZOrder Method


See Also

Events

Functions

Keywords by Task

Methods

Objects

Properties

Statements

Visual Basic Help


.


.


Using Visual Basic

How To Information Summary

Creating an application involves:

Learning Visual Basic

Creating the Interface

Setting Properties

Writing and Debugging Code

Creating Your Own Objects

Creating Distribution Media With the Setup Toolkit


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.

Insert 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

Graphical Objects

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

Assigning an Icon to a Form

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 and Debugging Code

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

Create 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 Watch Expressions

Deleting Watch Expressions

Editing Watch Expressions

Entering and Editing Code

Entering Declarations in Code

Executing a Specific Statement

Finding a Procedure

Importing a Text File into Code

Replacing Text in Code

Searching for Text in Code

Setting and Clearing Breakpoints

Splitting the Code Window into Panes

Turning Syntax Checking On or Off

Using Example Code from Help

Using Constants

Using the Immediate Pane

Using Watch Expressions


Using Language Elements

Attaching an Event Procedure to a Form or Control

Calling Windows API Functions

Creating a Database

Creating a Procedure

Creating Custom Colors

Entering Declarations in Code

Finding a Procedure

Querying a Database

Specifying Access Keys

Accessing External Databases


Debugging Code

Adding Watch Expressions

Continuing Execution

Debugging Checklist

Deleting Watch Expressions

Editing Watch Expressions

Entering and Editing Code

Executing a Specific Statement

Restarting Execution

Setting and Clearing Breakpoints

Starting Execution

Tracing Execution

Turning Syntax Checking On or Off

Using Example Code from Help

Using Instant Watch

Using the Immediate Pane

Using Watch Expressions


Processing Files

Importing a Text File into Code

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

Creating an OLE Server

Using Dynamic Data Exchange (DDE)

Using Custom Controls


Controlling Program Flow

Ending Execution

Executing a Specific Statement

Restarting Execution

Specifying a Startup Form

Starting Execution

Stopping Execution


Project Management

Importing a Text File into Code

Saving Your Work

Setup Toolkit Files

Setup Toolkit Overview

Using Example Code from Help


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.

Accessing Databases.

Introduction to OLE Automation Objects.

Using Color and Graphics.


Reference Information

Development Environment

Miscellaneous Information


Development Environment

Add Watch Dialog Box

Add-In Manager Dialog Box

Calls Dialog Box

Code Window

Color Palette

Custom Control Upgrade Dialog Box

Custom Controls Dialog Box

Debug Window

Edit Watch Dialog Box

EXE Options Dialog Box

Form Window

Insert Procedure Dialog Box

Instant Watch Dialog Box

Load Icon Dialog Box

Load Picture Dialog Box

Member Options Dialog Box

Menu Bar

Menu Editor

Menus & Commands

Multiple Procedure Instances Dialog Box

Object Browser

Options Dialog Box, Advanced Tab

Options Dialog Box, Editor Tab

Options Dialog Box, Environment Tab

Options Dialog Box, Project Tab

Project Window

Properties Window

References Dialog Box

Scroll Bar

Toolbar

Toolbox


Miscellaneous Information

Accessibility for People with Disabilities

Character Set

Data Type Summary

Document Conventions

Glossary

Keyboard Guide

Operator Summary

Visual Basic Constants

Visual Basic for Applications Constants


Creating Your Own Objects

Creating an OLE Server

Defining a Class in an OLE Server

Managing Versions of Your Application

OLE Fundamentals

Setting Member Options


{bmr closerht.mrb}How To Information Summary
How To Information Summary

A

16-Bit and 32-Bit Setup Files

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing Databases on CD-ROM

Accessing External Databases

Accessing Screen Properties

Activating Data Access Objects

Activating Security

Adding and Deleting Controls at Run Time

Adding and Deleting Menu Commands at Run Time

Adding Watch Expressions

Aligning an Item to the Grid

Assigning an Icon to a Form

Attaching an Event Procedure to a Form or Control

B

Binding a Control to a Data Control

Building SQL Statements in Code

C

Calling Windows API Functions

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Grid Spacing

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft Foxpro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings

Changing the System Database

Checking an Application for an Object Library

Choosing a Data Control Recordset Type

Choosing a Field Data Type

Command Line Switches

Compressing Files with COMPRESS.EXE

Compressing the Setup Files

Connecting an Add-in to Visual Basic

Connecting Help to an Application

Connecting to ODBC Databases

Connecting to the SourceSafe Add-In

Continuing Execution

Control Arrays

Controls

Converting a Database into a Replicable Form

Creating a Control Array

Creating a Database

Creating a DDE Source or Destination Link

Creating a General Procedure

Creating a Menu Bar

Creating a Menu Control Array

Creating a Network Server Distribution Directory

Creating a Procedure

Creating a Setup Disk for ODBC Applications (Professional Edition Only)

Creating Add-Ins

Creating an OLE Server

Creating an Object Variable

Creating Arrays

Creating Context Menus (Windows 95)

Creating Custom Colors

Creating Installation Options

Creating Parameter Queries

Creating Recursive Procedures

Creating the Distribution Media

Customizing Data Access .INI Settings

Customizing Windows Registry Settings for Data Access Objects

D

Debugging Checklist

Defining a Class in an OLE Server

Deleting Watch Expressions

Developing In-Process OLE Servers

Displaying Graphics on a Form

Displaying or Hiding the Grid

Drawing a Control

Drawing Lines and Shapes on a Form

E

Editing Watch Expressions

Ending Execution

Entering and Editing Code

Entering Declarations in Code

Examples of Converting Code to Jet Version 2.5

Executing a Specific Statement

F

Files You Are Allowed To Distribute

Files You Need to Distribute

Finding a Procedure

Formatting File Lists in [BOOTSTRAP] and [FILES]

G

Graphical Objects

H

How to Use the Setup Toolkit

I

Implementing the DBList and DBCombo Controls

Importing a Text File into Code

Including or Excluding Dependency Files

K

Keeping Objects Local Prior to Converting a Database into a Replicable Form

L

Layout of the Distribution Disks

Locking Behavior in Multiuser Applications

M

Making a Replica the Design-Master for the Replica Set

Making Additional Replicas

Making Faster For...Next Loops

Making Objects Replicable or Local

Managing Connections to ODBC Data Sources

Managing Versions of Your Application

Modifying SETUP.LST

Modifying the [BOOTSTRAP] Section of SETUP.LST

Modifying the [FILES] Section of SETUP.LST

Modifying the [SETUP] Section of SETUP.LST

Module Scope

Moving Design-Master Status to Another Replica

N

Naming-Conflict Errors

O

Obsolete Features in DAO

OLE Automation

OLE Controls Interoperability for 16- and 32-Bit Platforms

OLE Fundamentals

Opening a Database With the Data Control

P

Passing Arguments Efficiently

Populating Recordsets

Positioning the Current Record Pointer

Procedure Scope

Programming Restrictions for In-Process OLE Servers

Q

Querying a Database

R

Replacing Text in Code

Resolving Naming Conflicts

Resolving Synchronization Conflicts

Restarting Execution

Retrieving Data Using SQL

Returning Strings from Functions

S

Saving Space with Data Types

Saving Your Work

Scope and Visibility

Searching for Text in Code

Selecting a Recordset Type for Data Access Objects

Selecting Controls

Setting and Clearing Breakpoints

Setting Colors

Setting Form and Control Properties

Setting Member Options

Setting Options

Setting Tab Order

Setup Toolkit Files

Setup Toolkit Overview

Specifying a Startup Form

Specifying Access Keys

Specifying the OLE Link Format

Splitting the Code Window into Panes

Starting Execution

Stopping Execution

Synchronizing Replicas

T

Testing Your Setup Program

The SetupWizard vs. the SetupToolkit

Tracing Execution

Turning Syntax Checking On or Off

U

Using Bookmarks With the Microsoft Jet Version 2.5/3.0 Engine

Using Constants

Using Counter Fields

Using Custom Controls

Using Custom Properties Dialog Boxes

Using Data Types Efficiently

Using Dynamic Data Exchange (DDE)

Using Example Code from Help

Using Externally Creatable Objects

Using Instant Watch

Using MDI Features

Using Microsoft Jet Version 3.0 and 2.5

Using Named Arguments

Using Parameter Queries with the Data Control

Using Resource Files

Using SQL PassThrough

Using the DBGrid Control

Using the Immediate Pane

Using the MSysConf Table With SQL Databases

Using Watch Expressions

W

What is an In-Process OLE Server?

What is Database Replication?

What's New in Version 4.0

Where to Install Files on the User's Machine

Working Across Applications

Working with Add-In Objects

Working with OLE Automation Objects

Writing Data to Files

Writing Your Setup Program


Method Summary


Method Summary

See Also

A

Add

Add (Add-In)

Add (DBGrid)

AddFile (Add-In)

AddFormTemplate (Add-In)

AddItem

AddMDIFormTemplate (Add-In)

AddMenu (Add-In)

AddMenuTemplate (Add-In)

AddNew

AddReference (Add-In)

AddToolboxProgID (Add-In)

AddToolboxTypelib (Add-In)

AddToolboxVBX (Add-In)

Append

AppendChunk

Arrange

C

CancelUpdate

CellText

CellValue

Circle

Clear

Clear (Clipboard, ComboBox, ListBox)

Clone

Close

Close (OLE Container)

Cls

ColContaining

CompactDatabase

ConnectEvents (Add-In)

Copy

CopyQueryDef

CreateDatabase

CreateDynaset

CreateEmbed

CreateField

CreateGroup

CreateLink

CreateProperty

CreateQueryDef

CreateRelation

CreateSnapshot

CreateTableDef

CreateUser

CreateWorkspace

D

Delete

Delete (OLE Container)

DeleteQueryDef

DisconnectEvents (Add-In)

DoVerb

Drag

E

Edit

EndDoc

Execute

ExecuteSQL

F

FetchVerbs

FieldSize

FillCache

FindFirst

FindLast

FindNext

FindPrevious

G

GetBookmark

GetChunk

GetData

GetFormat

GetRows

GetText

H

Hide

I

Idle

InsertFile (Add-In)

InsertObjDlg

Item (Add-In)

Item

K

KillDoc

L

Line

LinkExecute

LinkPoke

LinkRequest

LinkSend

ListFields

ListIndexes

ListParameters

ListTables

LoadProject (Add-In)

M

MakeReplica

Move

Move (Data Access)

MoveFirst

MoveLast

MoveNext

MovePrevious

N

NewPage

NewPassword

O

OpenDatabase

OpenQueryDef

OpenRecordset

OpenTable

P

PaintPicture

Paste

PasteSpecialDlg

Point

PopupMenu

Print

PrintForm

PSet

R

Raise

ReadFromFile

Rebind

Refill

Refresh

Refresh (Data Access)

RefreshLink

RegisterDatabase

Reload (Add-In)

Remove

Remove (Add-In)

Remove (Data Access)

RemoveComponent (Add-In)

RemoveItem

RepairDatabase

Requery

RowBookmark

RowContaining

RowTop

S

SaveAs (Add-In)

SaveToFile

SaveToOle1File

Scale

ScaleX

ScaleY

Scroll

Seek

SetData

SetFocus

SetText

Show

ShowColor

ShowFont

ShowHelp

ShowOpen

ShowPrinter

ShowSave

ShowWhatsThis

Synchronize

T

TextHeight

TextWidth

U

Update (Data Access)

Update (OLE Container)

UpdateControls

UpdateRecord

W

WhatsThisMode

WriteProperty (Add-In)

Z

ZOrder


See Also

Data Access Methods

Events

Functions

Keywords by Task

Objects

Programming Language Summary

Properties

Statements

Visual Basic Help


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 object's Number property.  Unused error numbers in the range 1 to 1000 are reserved for future use by Visual Basic.

Note   The description "Application-defined or object-defined error" occurs when an error is generated using the Err object's Raise method or the Error statement, but the number does not correspond to an error defined by Visual Basic for applications.  Such errors may be defined by the host application (for example, Microsoft Excel or Visual Basic), but if you want to generate them from code, you must use the Raise method, and fill in all relevant arguments.

Remember, while developing in Visual Basic you can get information from Help on a message by pressing F1.

CommonDialog Control Messages

DDE and Form-Related Messages

Grid Messages

Miscellaneous Messages

OLE Automation Messages

OLE Container Control Messages


See Also

Application-defined or object-defined errors

CVErr Function

Err Object

Error Function

Error Statement

On Error Statement

Raise Method

Resume Statement

Trappable Data Access Errors

Visual Basic Help


Miscellaneous Messages

See Also

Code	Message

3	Return without GoSub

5	Invalid procedure call

6	Overflow

7	Out of memory

9	Subscript out of range

10	This array is fixed or temporarily locked

11	Division by zero

13	Type mismatch

14	Out of string space

16	Expression Too Complex

17	Can't perform requested operation

18	User interrupt occurred

20	Resume without error

28	Out of stack space

35	Sub, Function, or Property not defined

47	Too many DLL application clients

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

67	Too many files

68	Device unavailable

70	Permission denied

71	Disk not ready

74	Can't rename with different drive

75	Path/File access error

76	Path not found

91	Object variable or With block variable not set

92	For loop not initialized

93	Invalid pattern string

94	Invalid use of Null

444	Method not applicable in this context

452	Invalid ordinal

453	Specified DLL function not found

457	Duplicate Key

460	Invalid Clipboard format

461	Specified format doesn't match format of data

480	Can't create AutoRedraw image

481	Invalid picture

482	Printer error

483	Printer driver does not support specified property

484	Problem getting printer information from the system. Make sure the printer is set up correctly

485	Invalid picture type

520	Can't empty Clipboard

521	Can't open Clipboard


See Also

CommonDialog Control Messages

DDE and Form-Related Messages

Grid Messages

OLE Automation Messages

OLE Container Control Messages

Trappable Errors

Visual Basic Help


DDE and Form-Related Messages

See Also

Code	Message

260	No timer available

280	DDE channel not fully closed; awaiting response from foreign application

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 while waiting for DDE response

287	User pressed Escape 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

296	PasteLink already performed on this control

297	Can't set LinkMode; invalid Link Topic

298	System DLL 'dll'' could not be loaded (Error 298)

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

321	Invalid file format

325	Invalid format in resource file

326	Resource with identifier 'item' not found

335	Could not access system registry

336	Object server not correctly registered

337	Object server not found

338	Object server did not correctly run

340	Control array element 'item' doesn't exist

341	Invalid control array index

342	Not enough room to allocate control array 'item'

343	Object not an array

344	Must specify index for object array

345	Reached limit: cannot create any more controls for this form

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

366	No MDI form available to load

380	Invalid property value

381	Invalid property array index

382	'Item' property cannot be set at run time

383	'Item' property is read-only

384	A form can't be moved or sized while 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

389	Invalid key

390	No Defined Value

391	Name not available

393	'Item' property cannot be read at run time

394	'Item' property is write-only

395	Can't use separator bar as menu name

396	'Item' property cannot be set within a page

397	Can't set Visible property for top level menus while they are merged

400	Form already displayed; can't show modally

401	Can't show non-modal form when 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

419	Permission to use object denied

423	Property or method not found

424	Object required

426	Only one MDI Form allowed

427	Invalid object type; Menu control required

428	Popup menu must have at least one submenu


See Also

CommonDialog Control Messages

Grid Messages

Miscellaneous Messages

OLE Automation Messages

OLE Container Control Messages

Trappable Errors

Visual Basic Help


OLE Automation Messages

See Also

Code	Message

429	OLE Automation server cannot create object

430	Class doesn't support OLE Automation

432	File name or class name not found during OLE Automation operation

438	Object doesn't support this property or method

440	OLE Automation error

443	OLE Automation object does not have a default value

445	Object doesn't support this action

446	Object doesn't support named arguments

447	Object doesn't support current locale setting

448	Named argument not found

449	Argument not optional

450	Wrong number of arguments

451	Object not a collection


See Also

CommonDialog Control Messages

DDE and Form-Related Messages

Grid Messages

Miscellaneous Messages

OLE Container Control Messages

Trappable Errors

Visual Basic Help


Grid Messages

See Also

Code	Message

30000	Can not do a RemoveItem on a fixed row

30001	Cannot use AddItem on 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


See Also

CommonDialog Control Messages

DDE and Form-Related Messages

Miscellaneous Messages

OLE Automation Messages

OLE Container Control Messages

Trappable Errors

Visual Basic Help


OLE Container Control Messages

See Also

Code	Message

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

CommonDialog Control Messages

DDE and Form-Related Messages

Grid Messages

Miscellaneous Messages

OLE Automation Messages

Trappable Errors

Visual Basic Help


CommonDialog Control Messages

See Also

Code	Message

20476	The FileName buffer is too small to store the seleted file name(s)

20477	Invalid filename

20478	An attempt to subclass a ListBox failed due to insufficient memory

24574	No fonts exist

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

28661	The PrintDlg function failed when it attempted to create an information context

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

28663	A default printer does not exist

28664	No printer device drivers were found

28665	The PrintDlg function failed during initialization

28666	The printer device driver failed to initialize a DEVMODE data structure

28667	The PrintDlg function failed to load the specified printer's device driver

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

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

28670	Load of required resources failed

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

31001	Out of memory

32751	Help call fail.  Check Help properties.

32752	Low on memory!  Can't bring up the dialog!

32753	Couldn't determine procedure address(es).  \nSelect a different DLL.

32754	DLL selected couldn't be loaded

32755	Cancel was selected

32756	The ENABLEHOOK flag was set in the Flags member of a common dialog data structure but the application failed to provide a pointer to a corresponding hook function

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

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

32759	The common dialog function failed to lock a specified resource

32760	The common dialog function failed to load a specified resource

32761	The common dialog function failed to find a specified resource

32762	The common dialog function failed to load a specified string

32763	The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a corresponding instance handle

32764	The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a corresponding template

32765	The common dialog function failed during initialization

32766	The lStructSize member of the corresponding common dialog data structure is invalid


See Also

DDE and Form-Related Messages

Grid Messages

Miscellaneous Messages

OLE Automation Messages

OLE Container Control Messages

Trappable Errors

Visual Basic Help


Method not applicable in this context (444)

You can't use this method in the current event procedure.


Objects Summary


Objects Summary

See Also

A

App Object

Application Object (Add-In)

C

CheckBox Control

ClassModule Object

Clipboard Object

Collection Object

Column Object

Columns Collection

ComboBox Control

CommandButton Control

CommonDialog Control

Component Object (Add-In)

Components Collection (Add-In)

Container Object

Containers Collection

Controls Collection

ControlTemplate Object (Add-In)

ControlTemplates Collection (Add-In)

D

Data Control

Database Object

Databases Collection

DBCombo Control

DBEngine Object

DBGrid Control

DBList Control

Debug Object

DirListBox Control

Document Object

Documents Collection

DriveListBox Control

Dynaset Object

E

Err Object

Error Object

Errors Collection

F

Field Object

Fields Collection

FileControl Object (Add-In)

FileListBox Control

Font Object

Form Object

Forms Collection

FormTemplate Object (Add-In)

Frame Control

G

Grid Control

Group Object

Groups Collection

H

HScrollBar Control

I

Image Control

Index Object

Indexes Collection

L

Label Control

Line Control

ListBox Control

M

MDIForm Object

Menu Control

MenuItems Collection (Add-In)

MenuLine Object (Add-In)

O

OLE Container Control

OptionButton Control

P

Parameter Object

Parameters Collection

Picture Object

PictureBox Control

Printer Object

Printers Collection

ProjectTemplate Object (Add-In)

Properties Collection (Add-In)

Properties Collection (Data Access)

Property Object (Add-In)

Property Object (Data Access)

Q

QueryDef Object

QueryDefs Collection

R

Recordset Object

Recordsets Collection

Relation Object

Relations Collection

RowBuffer Object

S

Screen Object

SelBookmarks Collection

SelectedComponents Collection (Add-In)

SelectedControlTemplates Collection (Add-In)

Shape Control

Snapshot Object

SubMenu Object (Add-In)

T

Table Object

TableDef Object

TableDefs Collection

TextBox Control

Timer Control

U

User Object

Users Collection

V

VScrollBar Control

W

Workspace Object

Workspaces Collection


See Also

Data Access Objects and Collections

Events

Functions

Keywords by Task

Methods

Programming Language Summary

Properties

Statements

Visual Basic Help


Property Summary


Property Summary

See Also

A

AbsolutePosition

Action (CommonDialog)

Action (OLE Container)

ActiveControl

ActiveForm

ActiveProject (Add-In)

AddInMenu (Add-In)

Align

Alignment

AllowAddNew

AllowDelete

AllowRowSizing

AllowSizing

AllowUpdate

AllowZeroLength

AllPermissions

Appearance

AppIsRunning

Application (Add-In)

Archive

Attributes

AutoActivate

AutoRedraw

AutoShowChildren

AutoSize

AutoVerbMenu

B

BackColor

BackStyle

BOF

BOFAction

Bold

Bookmark Property (Data Access)

Bookmark Property (DBGrid)

Bookmarkable

BorderColor

BorderStyle

BorderWidth

BoundColumn

BoundText

C

CacheSize

CacheStart

Cancel

CancelError

Caption

CellSelected

Checked

Class

ClassName (Add-In)

Clip

ClipControls

Clustered

Col

ColAlignment

ColIndex

ColIsVisible

CollatingOrder

Color

ColorMode

ColPos

Cols

ColumnCount

ColumnHeaders

ColumnName

Columns (DBGrid)

Columns (ListBox)

ColWidth

Comments

CompanyName

ConflictTable

Connect

Container (Add-In)

Container (Data Access)

Container

ControlBox

ControlTemplates (Add-In)

Copies

Count (Data Access)

Count (VB Collections)

CurrentX

CurrentY

D

Data

Database

DatabaseName

DataChanged

DataField

DataMode

DataSource

DataText

DataUpdatable

DateCreated

Default

DefaultExt

DefaultPassword

DefaultUser

DefaultValue

DefColWidth

Description (ClassModule)

Description (Data Access)

Description

DesignMasterID

DeviceName

DialogTitle

DisplayType

DistinctCount

DividerStyle

DragIcon

DragMode

DrawMode

DrawStyle

DrawWidth

Drive

DriverName

Duplex

E

EditMode

Enabled

EOF

EOFAction

Exclusive

EXEName

F

Fields

FileControl (Add-In)

FileCount (Add-In)

FileDescription

FileName

FileNames (Add-In)

FileNumber

FileTitle

FillColor

FillStyle

Filter (CommonDialog)

Filter

FilterIndex

FirstRow

FixedAlignment

FixedCols

FixedRows

Flags (Color Dialog)

Flags (File Dialog)

Flags (Font Dialog)

Flags (Print Dialog)

Font

FontBold

FontCount

FontItalic

FontName

Fonts

FontSize

FontStrikethru

FontTransparent

FontUnderline

ForeColor

Foreign

ForeignName

ForeignTable

Format

FromPage

FullName (Add-In)

G

GridLines

GridLineWidth

H

Handle

hDC

HeadBackColor

HeadFont

HeadForeColor

HeadLines

Height

HelpCommand

HelpContext (CommonDialog)

HelpContext (Data Access)

HelpContext

HelpContextID

HelpFile (App, CommonDialog, MenuLine)

HelpFile (Data Access)

HelpFile

HelpKey

Hidden

HideSelection

HighLight

hInstance

HostName

hPal

hWnd

I

Icon

IconState (Add-In)

IgnoreNulls

Image

Index (Control Array)

Index (Data Access)

IndexedValue (Add-In)

Inherit

Inherited (Data Access)

IniPath

InitDir

Instancing

IntegralHeight

Interval

IsDirty (Add-In)

IsolateODBCTrans

Italic

ItemData

K

KeepLocal

KeyPreview

L

LargeChange

LastDLLError

LastModified

LastUpdated

LastUsedPath (Add-In)

LBound

Left

LeftCol

LegalCopyright

LegalTrademarks

LinkItem

LinkMode

LinkTimeout

LinkTopic

List

ListCount

ListField

ListIndex

Locked

LockEdits

LoginTimeout

LogMessages

lpOleObject

M

Major

MatchedWithList

MatchEntry

Max (CommonDialog)

Max (Scroll Bar)

MaxButton

MaxFileSize

MaxLength

MDIChild

MenuItems (Add-In)

Min (CommonDialog)

Min (Scroll Bar)

MinButton

Minor

MiscFlags

MouseIcon

MousePointer

MultiLine

MultiSelect

N

Name

Negotiate

NegotiateMenus

NegotiatePosition

NegotiateToolbars

NewEnum (Add-In)

NewIndex

NoMatch

Normal

Number (Data Access)

Number

NumberFormat

NumIndices (Add-In)

O

Object (OLE Container)

Object

ObjectAcceptFormats

ObjectAcceptFormatsCount

ObjectGetFormats

ObjectGetFormatsCount

ObjectVerbFlags

ObjectVerbs

ObjectVerbsCount

ODBCTimeout

OLEDropAllowed

OLERequestPendingMsgText

OLERequestPendingMsgTitle

OLERequestPendingTimeout

OLEServerBusyMsgText

OLEServerBusyMsgTitle

OLEServerBusyRaiseError

OLEServerBusyTimeout

OLEType

OLETypeAllowed

Options

OrdinalPosition

Orientation

Owner

P

Page

PaperBin

PaperSize

Parent

Password

PasswordChar

PasteOK

Path

Pattern

PercentPosition

Permissions

Picture

PID

Port

PrevInstance

Primary

PrinterDefault

PrintQuality

ProductName

Properties (Add-In)

Public

Q

QueryTimeout

R

ReadOnly (Data Access)

ReadOnly

ReadOnlyMode (Add-In)

RecordCount

RecordsAffected

RecordSelectors

Recordset

RecordsetType

RecordSource

Replicable

ReplicaID

Required

Restartable

ReturnsRecords

Revision

Row

RowCount (DBGrid)

RowDividerStyle

RowHeight

RowIsVisible

RowPos

Rows

RowSource

S

ScaleHeight

ScaleLeft

ScaleMode

ScaleTop

ScaleWidth

ScrollBars

SelBookmarks

SelCount

Selected

SelectedComponents (Add-In)

SelectedControlTemplates (Add-In)

SelectedItem

SelEndCol

SelEndRow

SelLength

SelStart

SelStartCol

SelStartRow

SelText

Shape

Shortcut

ShowInTaskbar (Windows 95)

Size (Data Access)

Size (Font)

SizeMode

SmallChange

Sort

Sorted

Source (Data Access)

Source

SourceDoc

SourceField

SourceItem

SourceTable

SourceTableName

SQL

StartMode

Stretch

StrikeThrough

Style

System

T

TabIndex

Table

TabStop

Tag

TaskVisible

Text

Title

Top

ToPage

TopIndex

TopRow

TrackDefault

Transactions

TwipsPerPixelX

TwipsPerPixelY

Type (Data Access)

Type (Picture)

U

UBound

Underline

Unique

Updatable

UpdateOptions

UseMnemonic

UserName

V

V1xNullBehavior

ValidateOnSet

ValidationRule

ValidationText

Value (Add-In)

Value (Data Access)

Value (RowBuffer)

Value

Verb

Version (Add-In)

Version

Visible

VisibleCols

VisibleCount

VisibleItems

VisibleRows

W

Weight

WhatsThisButton (Windows 95)

WhatsThisHelp (Windows 95)

WhatsThisHelpID (Windows 95)

Width

WindowList

WindowState

WordWrap

X

X1

X2

Y

Y1

Y2

Z

Zoom


See Also

Data Access Properties

Events

Functions

Keywords by Task

Methods

Objects

Programming Language Summary

Statements

Visual Basic Help


Keywords by Task


Keywords by Task

See Also

Category	Description

Arrays	Creating, defining, and using arrays.

Compiler Directives	Controlling compiler behavior.

Control Flow	Looping and controlling procedure flow.

Conversion	Converting numbers and data types.

Data Types	Data types and variant subtypes.

Dates and Times	Converting and using date and time expressions.

Directories and Files	Controlling the file system and processing files.

Errors	Trapping and returning error values.

Financial	Performing financial calculations.

Input and Output	Receiving input and displaying or printing output.

Math	Performing trigonometric and other mathematical calculations.

Miscellaneous	Starting other applications and processing events.

Operators	Comparing expressions and other operations.

String Manipulation	Manipulating strings and string type data.

Variables and Constants	Declaring and defining variables and constants.


See Also

Programming Language Summary

Visual Basic Help


Statement Summary


Statement Summary

See Also

A

AppActivate

B

Beep

BeginTrans

C

Call

ChDir

ChDrive

Close

CommitTrans

CompactDatabase

Const

D

Date

Declare

DefBool (Deftypes)

DefByte (Deftypes)

DefCur (Deftypes)

DefDate (Deftypes)

DefDbl (Deftypes)

DefInt (Deftypes)

DefLng (Deftypes)

DefObj (Deftypes)

DefSng (Deftypes)

DefStr (Deftypes)

DefVar (Deftypes)

DeleteSetting

Dim

Do...Loop

E

Each (For Each...Next)

Else (If...Then...Else)

End

Erase

Error

Exit

F

FileCopy

For Each...Next

For...Next

FreeLocks

Function

G

Get

GoSub...Return

GoTo

I

If...Then...Else

Input #

K

Kill

L

Let

Line Input #

Load

Lock...Unlock

Loop (Do...Loop)

LSet

M

Mid

MkDir

N

Next (For Each...Next)

Name

O

On Error

On GoSub

On Goto

Open

Option Base

Option Compare

Option Explicit

Option Private

P

Print #

Private

Property Get

Property Let

Property Set

Public

Put

R

Randomize

ReDim

RegisterDatabase

Rem

RepairDatabase

Reset

Resume

Return (GoSub...Return)

RmDir

Rollback

RSet

S

SavePicture

SaveSetting

Seek

Select Case

SendKeys

Set

SetAttr

SetDataAccessOption

SetDefaultWorkspace

Static

Stop

Sub

T

Then (If...Then...Else)

Time

Type

U

Unload

Unlock (Lock...Unlock)

W

While...Wend

Width #

With

Write #


See Also

Events

Functions

Keywords by Task

Methods

Objects

Programming Language Summary

Properties

Visual Basic Help


Keyboard Guide


Keyboard Guide

See Also

Code Window Keys

Debug Window Keys

Form Window Keys

Global Keys

Menu Editor Keys

Project Window Keys

Properties Window Keys

Toolbox Keys


See Also

Visual Basic Help


Global Keys

See Also

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+G	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+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.

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.


See Also

Debug Window Keys


Code Window Keys

See Also

General Use Keys

Use these key combinations in the Code window:

Press	To

F1	Get context-sensitive Help on functions, statements, methods, properties, or events.

F2	Display the Object Browser.

F9	Set or remove a breakpoint.

CTRL+SHIFT+F9	Clear all breakpoints.

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.

Navigation Keys

Use these key combinations to navigate in the Code window:

Press	To

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+SHIFT+F2	Go back to the last position in your code.

CTRL+HOME	Go to the beginning of the module.

CTRL+END	Go to the end of the module.

CTRL+RIGHT	Go one word to the right.

CTRL+LEFT	Go one word to the left.

END	Go to the end of the line.

HOME	Go to the beginning of the line.

CTRL+PAGE DOWN	Go to the bottom of the current procedure.

CTRL+PAGE UP	Go to the top of the current procedure.

F6	Switch between Code window panes (when the window is split).

Code Editing Keys

Use these key combinations to edit code in the Code window:

Press	To

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.

CTRL+DEL	Delete to the end of the word.

CTRL+BACKSPACE	Delete to the beginning of the word.

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.

SHIFT+TAB	Remove indent.

Menu Shortcut Keys

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+H	Replace.

SHIFT+F9	Instant Watch (break mode only).

CTRL+W	Edit Watch.

CTRL+L	Calls Window (break mode only).

CTRL+G	Debug window (break mode only).


See Also

Code Window

Debug Window

Find Command (Edit Menu)


Form Window Keys

See Also

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 Properties window for the selected property.

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+E	Display the Menu Editor (design time only).

F4	Display the Properties window (design time only).

CTRL+J	Bring to front (affects overlapping controls at design time only).

CTRL+K	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.


See Also

Code Window

Form Window

Menu Editor

Properties Window


Debug Window Keys

See Also

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).

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 the Object Browser.

CTRL+ENTER	Insert carriage return.

F6	Switch between the Immediate pane and the Watch pane (if visible) in the Debug window.

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 the Object Browser.

F6	Switch between the Watch pane and the Immediate pane in the Debug window.

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.


See Also

Debug Window


Menu Editor Keys

See Also

Use these key combinations in the Menu Editor:

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 Editor:

Press	To

F4	Open or close the list.

ALT+DOWN ARROW	Open or close the list.

ALT+UP ARROW	Open or close the list.

END	Move to the last item in the list.

HOME	Move to the first item in the list.


See Also

Menu Editor


Properties Window Keys

See Also

Use these key combinations when the Property list has the focus in the Properties window:

Press	To

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 property's 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 for a property 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 its 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.

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).


See Also

BackColor, ForeColor

BorderColor

Color Palette

Icon Property

FillColor Property

Picture Property

Properties Window


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

See Also

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.


See Also

Code Window

Project Window

Toolbox


The file, 'item', is invalid.  Only forms, modules, and classes can be added to the project using Add File.  Use the Tools menu
The file, 'item', is invalid.  Only forms, modules, and classes can be added to the project using Add File.  Use the Tools menu in order to add Controls or References to the project.

Only certain file formats can be loaded into a project using the Add File command.  Choose Custom Controls or References from the Tools menu to load a custom control or to add a reference to a library.


Unrecoverable Error: A project could not be created, terminating Visual Basic.

Visual Basic encountered an unexpected error from which it can't recover.  Try to start Visual Basic again and load or create a project.  If the unrecoverable error reoccurs, reboot your system and try again.


Item' is a VB1 form and cannot be loaded into VB4.
'Item' is a VB1 form and cannot be loaded into VB4.

Forms created with Visual Basic 1.0 can't be loaded into Visual Basic 4.0.  If you have a copy of Visual Basic 2.0 or 3.0, you can load the form created with version 1.0 and save it as text.  Then you can load the form in Visual Basic 4.0.


The basic code in 'item' was corrupt, and couldn't be loaded.

Visual Basic couldn't load the code portion of a Visual Basic 2.0 or 3.0 file that was saved in binary format and the file is corrupt.  If it's an .FRM file, the form itself (but no code) is loaded.  If it's a .BAS file, the entire file can't be loaded.


Can't display system information

Visual Basic can't display system information when you choose System Info from the About Microsoft Visual Basic dialog box.  Your system may not have enough memory or a required file may be corrupted or missing.


Separator may not be checked or disabled, or have a shortcut key

While working with the Menu Editor tool, you tried to set a separator menu item's Checked property to True or its Enabled property to False or you tried to assign it a shortcut key.  A separator menu item can't have any of these property settings, but you can set its Visible property to False.


Only Top Level Menus can have non-zero NegotiatePosition.
Only Top Level Menus can have non-zero NegotiatePosition

You tried to set the NegotiatePosition property for a menu item other than a top-level menu.


Project Name 'item' is invalid

The name you tried to assign to a project is invalid.  A project name:

Must be no longer than 40 characters.

Can't be a reserved word.

Can't have a space or punctuation characters.

Can't have an international or double-byte character.


Project too large too make into an EXE
Project too large to make into an .EXE

This 16-bit project exceeded the absolute size for an .EXE file that the operating system can handle.  You must reduce the size of the project or break it up into pieces.  The maximum size of a project's .EXE file varies, but anything over 10 megabytes may be too large and 32 megabytes is the upper limit.

This situation can only occur with the 16-bit version of Visual Basic.


Version numbers must be in the range 0 to 9999

You tried to assign a negative number or a non-numeric character as the Major, Minor, or Revision component of the Version number for an .EXE file in the EXE Options dialog box.  Use a number between 0 and 9999 inclusive.


Only one resource file allowed

You chose Add File from the File menu and tried to add a second .RES file to your project or the .VBP file lists more than one .RES file.  You can only have one Windows resource file in a Visual Basic project.


Duplicate resources with same type and name

The Windows resource file you are trying to use in your project contains two or more resources with the same type and name, or the resource file has a resource that Visual Basic automatically creates.

Use another resource file or recreate the invalid resource file and delete one of the duplicate resources.


Programmatic ID string too long 'item
Programmatic ID string too long 'item'

The ProgID string of the OLE server can't be longer than 39 characters.  The ProgID is created by concatenating the project name with the class module name.


The name 'item' contains invalid characters when part of a Programmatic ID

The ProgID string of the OLE server contains invalid characters.  The ProgID is created by concatenating the project name with the class module name.  Although the individual project and class module names were valid, the concatenation of the two names into the ProgID string violated a constraint specific to ProgID strings.


Registration information too large to make into an EXE
Registration information too large to make into an .EXE

You chose Make EXE File from the File menu to build an OLE server, but Visual Basic couldn't create it because the number of Public classes you defined in your OLE server exceeded the limits of the information that can be registered.

The amount of registration information stored in an OLE server's .EXE depends on:

The number of previous versions of the OLE server with which the Public class is upwardly compatible.

The length of the ProgID of the class.

The length of the description of the class module.


OLE server could not be created

An OLE server or instance of it couldn't be created with the CreateObject function, or you chose Make EXE File from the File menu to build an OLE server, but Visual Basic couldn't create the file.


The Public property for Class 'item' cannot be set to True.  You do not have an appropriate license to use this functionality in
The Public property for Class 'item' cannot be set to True.  You do not have an appropriate license to use this functionality in the design environment.

You can only make Public class modules (OLE server accessible from outside the project) with the Professional edition of Visual Basic 4.0.  The Standard edition doesn't have a license to do this.


The file 'item' does not contain information needed to create a compatible OLE server.

The filename you entered in the Compatible OLE server field of the Project Options dialog box isn't an Visual Basic-created .EXE with Public class modules.


Do you want to upgrade all 'item1' objects in this project to 'item2' objects?

The class of the specified object has changed.  Choose Yes to upgrade all instances of the specified object in this project to reflect the changes made to the class or choose No if you don't want to upgrade.


The class name of the newly upgraded 'item1' objects is 'item2'.  Since this is different from their previous name of 'item3', y
The class name of the newly upgraded 'item1' objects is 'item2'.  Since this is different from their previous name of 'item3', you must change any declarations of this object that you have in code.

The class name of the specified object you upgraded has changed.  You must change any declarations of the specified object in your code to refer to the new class name.


Could not find Data Access Library.  Cannot Create reference.

Visual Basic tried to create a reference to the Microsoft DAO 2.5 Object Library through the Data control but failed.  You should verify that all system registry keys are valid and, if they are not, run Visual Basic setup again.


Can't exit Windows while an OLE object is active for editing.

You tried to exit Windows while an OLE object was active.  Deactivate the OLE object before quitting Windows.


Binary Translator, VBTRANS.EXE, could not be run.  Basic module 'item' not loaded.

The specified .BAS file is in binary format; but Visual Basic couldn't launch VBTRANS.EXE to convert it to ASCII format so it couldn't load the module file.  Make sure that an uncorrupted copy of VBTRANS.EXE exists on the same path as VB.EXE.


Binary Translator, VBTRANS.EXE, could not be run.  Code portion of form 'item' not loaded.

The specified .FRM file is in binary format; but Visual Basic couldn't launch VBTRANS.EXE to convert it to ASCII format so it couldn't load the code portion of the form file.  Make sure that an uncorrupted copy of VBTRANS.EXE exists on the same path as VB.EXE.


Other applications are currently accessing a server in your program.  Ending the program now could cause errors in those program
Other applications are currently accessing a server in your program.  Ending the program now could cause errors in those programs.  End program at this time?

An OLE Automation object in the Visual Basic program you are currently running is being accessed by at least one other application.  Terminating your program could cause an error in the other application.  Choose Yes to quit your program or choose No to continue it.


One or more of the properties in 'item' was bad.  Some or all of the properties might not be set correctly.

The specified .VBP file has one or more invalid property settings.  This error occurs only in regard to a project's .VBP file.


Item' could not be registered
'Item' could not be registered

The specified file couldn't be registered in the system registry.  The error is related to type libraries used by components of the Visual Basic development environment (for example, OC25.DLL, VB.OLB, DAO2516.DLL) and indicates that the specified file's entry in the system registry is corrupted or that the DLL itself is missing or corrupted.


Item' could not be loaded.  Remove it from the list of available Add-Ins?
'Item' could not be loaded.  Remove it from the list of available Add-Ins?

Visual Basic couldn't load the add-in that you tried to select from the Available Add-Ins list in the Add-In Manager dialog box.  Choose Yes to remove it from the list or choose No to leave it on the list.  In either case, you can't load it.


Visual Basic cannot load 'item' because it is not in the system registry.  Please ensure that all Add-Ins have been installed co
Visual Basic cannot load 'item' because it is not in the system registry.  Please ensure that all Add-Ins have been installed correctly.

Visual Basic couldn't load the add-in that you tried to select from the Available Add-Ins list in the Add-In Manager dialog box, because it was not registered properly or is no longer registered in the system registry.


The form name for file 'item' is different than the module name.  Visual Basic will use the form name.

There is a conflict in the ASCII file between the name of the form (for example, Form1 in the Begin VB.Form Form1 statement) and the module name specified in the Attribute VB.Name statement.  To resolve the conflict, Visual Basic uses the name of the form in the Begin VB.Form statement.

This error normally occurs only if you have been manually editing an ASCII form file.


Forms must always be non-public and non-creatable.  Resetting form 'item' to default values.

Only a class module can have its attributes in an ASCII form file set to VB-Creatable and VB-Exposed, so Visual Basic is resetting the form to non-Creatable and non-Exposed.

This error normally occurs only if you have been manually editing an ASCII form file.


Visual Basic can't upgrade the custom controls to those provided in the 'item' library.  Remove this library from the list of av
Visual Basic can't upgrade the custom controls to those provided in the 'item' library.  Remove this library from the list of available upgrades?

Visual Basic was unable to convert one or more VBX custom controls to OLE custom controls.  Choose Yes to remove the library reference from the list so that VB won't try to upgrade the specified VBX custom controls again, or choose No to leave the library in the list.


Item' is a class name
'Item' is a class name

The specified identifier is being used as the class name of a control or form.  Use another name.


A module with this name exists

You can't have two modules with the same name.  Save the module with another name.


Can't delete module; must Re-Initialize first

Visual Basic can't delete this module without returning to design time.


Incompatible version of WIN87EM.DLL; quitting

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).


Not enough memory to run; quitting

Visual Basic couldn't obtain enough memory to run.  Close other applications and try again.


Not enough memory to load file

Visual Basic couldn't obtain enough memory to load the file.  Close other applications and try again.


Stop statement encountered

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


Unexpected error; quitting

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


Wrong version of run-time DLL

Visual Basic can't find VBRUN400.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 \SYSTEM directory.


Can't copy (Error 31009)

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 (Error 31003)

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 (Error 31007)

See Also

The Clipboard doesn't 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 container 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) and then delete the object (set Action = 10), the object on the Clipboard is also deleted.


See Also

PasteOK Property


Class is not set (Error 31018)

See Also

When setting Action = 0 (CreateEmbed method) and you don't 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 container control with the right mouse button and choose the Insert Object command.


See Also

Class Property

SourceDoc Property


Dialog already in use (Error 31029)

Only one OLE dialog box (either Insert Object or Paste Special) can be displayed at a time.


Error loading from file (Error 31037)

See Also

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 wasn't saved properly (set Action = 11).

The file is corrupted.

The file position isn't located at the beginning of a valid OLE object.


See Also

Action Property

FileNumber Property


Error saving to file (Error 31036)

See Also

Visual Basic can't 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.

There isn't enough disk space.


See Also

Action Property

FileNumber Property


Invalid Action (Error 31021)

See Also

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 container control:

2

3

8

13

16


See Also

Action Property


Incorrect Clipboard format (Error 31035)

See Also

The OleTypeAllowed property doesn't match the type of object on the Clipboard.


See Also

OleTypeAllowed Property


Invalid format (Error 31017)

See Also

You attempted to set or get data with the Data or DataText property using an invalid data format or a format the object doesn't support.

To determine the set of valid formats for an OLE object, use the ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, and ObjectGetFormatsCount properties.


See Also

Data Property

DataText Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


Invalid or unknown class (Error 31023)

See Also

The specified Class property isn't valid and the SourceDoc property isn't specified.

To display a list of the available class names on your system, at design time click the OLE container 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.


See Also

Class Property

SourceDoc Property


Invalid property value (Error 31008)

You 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 (Error 31031)

See Also

You attempted to create a linked object (set Action = 1) and the file specified by the SourceDoc property couldn't be found.


See Also

SourceDoc Property


Invalid Verb index (Error 31034)

See Also

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.


See Also

ObjectVerbs Property

ObjectVerbsCount Property

Verb Property


Source name is too long (Error 31026)

See Also

The combined number of characters in the SourceDoc and SourceItem strings can't exceed 256.


See Also

SourceDoc Property

SourceItem Property


No object (Error 31004)

You tried to perform an action on an object that doesn't exist.


Object not running (Error 31028)

See Also

You can't 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.


See Also

AppIsRunning Property

Verb Property


Source Document is not set (Error 31019)

See Also

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 filename.


See Also

SourceDoc Property


This control requires Visual Basic version 3.0 or later (Error 31038)

The OLE container control isn't compatible with Visual Basic versions 1.0 and 2.0.


Unable to access source document (Error 31039)

See Also

You attempted to create an embedded object, but the file specified by the SourceDoc property isn't a valid file.


See Also

SourceDoc Property


Unable to activate object (Error 31027)

See Also

The object's source document can't be loaded, or the application that created the object isn't 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 isn't 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 property list.  However, some verbs may not be valid for the application's current state.


See Also

ObjectVerbs Property

SourceDoc Property

Verb Property


Unable to close object (Error 31006)

The object can't be closed (Action = 10) in its current state.


Unable to create embedded object (Error 31032)

See Also

The application that is creating the object can't create the object as specified in the SourceDoc property.

For example, this error occurs if you try to embed a spreadsheet object and SourceDoc specifies a spreadsheet that is too large to be loaded by the spreadsheet application.


See Also

SourceDoc Property


Unable to create link (Error 31024)

See Also

The application that is creating the object can't 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 SourceDoc specifies a spreadsheet that is too large to be loaded by the spreadsheet application.


See Also

SourceDoc Property

SourceItem Property


Unable to fetch link source name (Error 31033)

The OLE container control can't 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 container control must determine the name of the source document based on the information provided by the Clipboard.  If the OLE container control can't determine the name of the document to link to, this error occurs.


Unable to initialize OLE (Error 31022)

OLE can't be initialized.  Make sure all the current OLE 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 requires Microsoft Windows version 3.1 or later.


A default printer does not exist (Error 28663)

Check the system for installed printers using the Printers collection.  If there are printers installed, set the Printer object to one of the printers in the Printers collection to define a default printer.


An attempt to subclass a ListBox failed due to insufficient memory (Error 20478)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Cancel was selected (Error 32755)

This error occurs when the CancelError property is set to True and the user clicks the Cancel button in the dialog box.  Use this error to execute different code when the Cancel button was selected.  For example, in a File Open dialog box, you might respond to this error by exiting the current procedure instead of attempting to open a file.


Couldn't determine procedure address(es).  \nSelect a different DLL (Error 32753)
Couldn't determine procedure address(es).  Select a different DLL (Error 32753)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


DLL selected couldn't be loaded (Error 32754)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Help call fail.  Check Help properties (Error 32751)

Check to make sure the HelpContextID and HelpFile properties are set to proper values for the Help file used by the application.


Invalid filename (Error 20477)

The specified filename may not exist or may contain illegal characters.


Load of required resources failed (Error 28670)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Low on memory!  Can't bring up the dialog! (Error 32752)

This error occurs when sufficient memory isn't available.  Check for sufficient system memory as well as available system resources.


No fonts exist (Error 24574)

Before displaying the Choose Font dialog box, you must set one of the following flags:

ScreenFonts

PrinterFonts

Both


No printer device drivers were found (Error 28664)

The system may not have printer drivers installed or the drivers may be missing.


The common dialog function failed during initialization (Error 32765)

This error often occurs when sufficient memory isn't available.


The common dialog function failed to find a specified string (Error 32761)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The common dialog function failed to load a specified resource (Error 32760)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The common dialog function failed to load a specified string (Error 32762)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The common dialog function failed to lock a specified resource (Error 32759)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


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

This error occurs when the information in WIN.INI can't be read by the CommonDialog control.  For example, the WIN.INI entry may contain the string "LDT1" instead of "LPT1" to identify a port.


The common dialog function was unable to allocate memory for internal data structures (Error 32758)

This error is caused by insufficient memory.


The common dialog function was unable to lock the memory associated with a handle (Error 32757)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The data in the DEVMODE and DEVNAMES data structures describes two different printers (Error 28662)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The ENABLEHOOK flag was set in the Flags member of a common dialog data structure but the application failed to provide a pointe
The ENABLEHOOK flag was set in the Flags member of a common dialog data structure but the application failed to provide a pointer to a corresponding hook function (Error 32756)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a co
The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a corresponding instance handle (Error 32763)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a co
The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a corresponding template

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The FileName buffer is too small to store the selected file name(s) (Error 20476)

This error occurs when the MaxFileSize property is too small to allocate enough space in memory for the selected file name(s).  Increase the setting of the MaxFileSize property.


The lStructSize member of the corresponding common dialog data structure is invalid (Error 32766)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


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

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The PD_RETURNDEFAULT flag was set in the Flags member of the PRINTDLG data structure but either the hDevMode or hDevNames field
The PD_RETURNDEFAULT flag was set in the Flags member of the PRINTDLG data structure but either the hDevMode or hDevNames field was nonzero (Error 28668)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The PrintDlg function failed during initialization (Error 28665)

This error is usually caused by insufficient memory.


The PrintDlg function failed to load the specified printer's device driver (Error 28667)

This error could be caused by a defective printer driver or a corruption in system memory.

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The PrintDlg function failed when it attempted to create an information context (Error 28661)

The amount of available system resources may be too low.


The printer device driver failed to initialization a DEVMODE data structure (Error 28666)
The printer device driver failed to initialize a DEVMODE data structure (Error 28666)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.  This error only applies to printer drivers written for Windows version 3.0 or later.


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

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Picture Object

See Also	Properties	Methods

The Picture object gives you a way to manipulate bitmaps, icons, and metafiles assigned to objects having a Picture property.

Syntax

Picture

Remarks

You frequently identify a Picture object using the Picture property of an object that displays graphics (such as a Form object or the PictureBox control).  If you have a PictureBox control, named Picture1, you can set one Picture object equal to another using the Set statement, as in the following example:

Dim X As Picture

Set X = LoadPicture("PARTY.BMP")

Picture1.Picture = X

You can use an array of Picture objects to keep a series of graphics in memory without needing a form that contains multiple PictureBox or Image controls.

You cannot create a Picture object using code like Dim X As New Picture.  If you want to create a Picture object, you must use the StdPicture object like this:

Dim X As New StdPicture


See Also

LoadPicture Function

PictureBox Control

Picture Property

Set Statement


Picture Object Properties

Handle Property

Height Property

hPal Property

Type Property

Width Property


Picture Object Methods

Render Method


Handle Property

See Also	Applies To

Returns a handle to the graphic contained within a Picture object.

Syntax

object.Handle

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Value

The value returned by the Handle property depends on the current setting of the Type property as shown in the following table:

Type Property	Return Value

1 (Bitmap)	An HBITMAP handle.

2 (Metafile)	An HMETAFILE handle.

3 (Icon)	An HICON or an HCURSOR handle.

Remarks

The Handle property is useful when you need to pass a handle to a graphic as part of a call to a function in a dynamic-link library or the Windows API.


See Also

Type Property


Handle Property Applies To

Picture Object


hPal Property

Applies To

Returns or sets a handle to the palette of a picture in a Picture object.

Syntax

object.hPal [= value]

The hPal property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	The handle to the palette for the picture (HPAL).

Remarks

The hPal property is useful when you need to pass a handle to a palette as part of a call to a function in a dynamic-link library or the Windows API.


hPal Property Applies To

Picture Object


Render Method

See Also	Applies To

Draws all or part of a source image to a destination object.

Syntax

object.Render(hdc, xdest, ydest, destwid, desthgt, xsrc, ysrc, srcwid, srchgt, wbounds)

The Render method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

hdc	Required.  The handle to the destination object's device context.

xdest	Required.  The x-coordinate of upper left corner of the drawing region in the destination object.  This coordinate is in the scale units of the destination object.

ydest	Required.  The y-coordinate of upper left corner of the drawing region in the destination object.  This coordinate is in the scale units of the destination object.

destwid	Required.  The width of drawing region in the destination object, expressed in the scale units of the destination object.

desthgt	Required.  The height of drawing region in the destination object, expressed in the scale units of the destination object.

xsrc	Required.  The x-coordinate of upper left corner of the drawing region in the source object.  This coordinate is in HIMETRIC units.

ysrc	Required.  The y-coordinate of upper left corner of the drawing region in the source object.  This coordinate is in HIMETRIC units.

srcwid	Required.  The width of drawing region in the source object, expressed in HIMETRIC units.

srchgt	Required.  The height of drawing region in the source object, expressed in HIMETRIC units.

wbounds	Required.  The world bounds of a metafile.  This argument should be passed a value of NULL unless drawing to a metafile, in which case the argument is passed a user-defined type corresponding to a RECTL structure.

Remarks

The best way to paint part of a graphic into a destination is through the PaintPicture method.


See Also

PaintPicture Method


Render Method Applies To

Picture Object


Creating Distribution Media with the Setup Toolkit


Creating Distribution Media with the Setup Toolkit

The Visual Basic Setup Toolkit provides tools to create setup programs for your Visual Basic applications.

Setup Toolkit Overview

The Setup Wizard vs. the Setup Toolkit

How to Use the Setup Toolkit

Setup Toolkit Files

16-Bit and 32-Bit Setup Files

Files You Need to Distribute

Files You Are Allowed to Distribute

Including or Excluding Dependency Files

Writing Your Setup Program

Compressing the Setup Files

Layout of the Distribution Disks

Where to Install Files on the User's Machine

Modifying SETUP.LST

Creating the Distribution Media

Creating a Network Server Distribution Directory

Testing Your Setup Program

Creating Installation Options

Creating a Setup Disk for ODBC Applications (Professional and Enterprise Editions Only)

Application Removal (32-bit only)

Application Removal Failure Scenarios

Client Registration Utility


The SetupWizard vs. the Setup Toolkit

See Also

If you don't need a customized setup program, use the Visual Basic SetupWizard to create your distribution media.  The SetupWizard:

Automatically builds an executable (.EXE) or in-proc server dynamic-link library (.DLL) file for your project.

Creates a setup program for your Visual Basic application.

Compresses all files and automatically splits files among disks.

Notifies you of dependency files your users need for your application to run correctly.

Notifies you of the number of blank formatted disks needed if you're distributing your application on disks.

Optionally copies distribution files to a hard disk for network distribution or transfer to a CD-ROM generation system.

Automatically determines to which directories your applications will be copied.

Automatically creates a SETUP.LST file.

Automatically creates a program group and an icon for your application.

If you need to customize your setup program, you can also use the Setup Toolkit, which is a set of utilities, DLLs, and a sample setup program written in Visual Basic.  The Setup Toolkit lets you:

Customize a setup program with the sample setup program supplied with Visual Basic.

Compress and expand your application's files.

Install files in the appropriate Microsoft Windows directories.

Create Windows Program Manager groups and icons (Windows for Workgroups or Windows NT) or Start Menu links (Windows 95) for your application.

You can use the SetupWizard with the Setup Toolkit to add dialog boxes to the installation program; the dialog boxes prompt the user to specify whether to install optional features in your application.


See Also

Creating Distribution Media with the Setup Toolkit

How to Use the Setup Toolkit

Setup Toolkit Overview


16-Bit and 32-Bit Setup Files

See Also

The setup files you use to create the distribution media for your application depend on whether you are using a 16-bit or 32-bit version of Visual Basic.  The following table lists where those files are installed on your machine.

Description	Version	Path and filename

SetupWizard files	16-bit 	SETUPWIZ.EXE, SETUP.EXE, SETUP.LST, and VBSKCO16.DLL are located in the \VB\SETUPKIT\KITFILES subdirectory.

32-bit	SETUPWIZ.EXE, SETUP.EXE, SETUP.LST, and VBSKCO32.DLL are located in the \VB\SETUPKIT\KITFIL32 subdirectory.

Setup Toolkit DLLs	16-bit	STKIT416.DLL is located in the \WINDOWS\SYSTEM subdirectory.

32-bit	STKIT432.DLL is located in the \WINDOWS\SYSTEM32 subdirectory.

Setup Toolkit files	16-bit	SETUP1.EXE is located in the \VB\SETUPKIT\SETUP1 subdirectory.

32-bit	SETUP132.EXE is located in the \VB\SETUPKIT\SETUP1 subdirectory.

ST4UNST.EXE is located in the \VB\SETUPKIT\KITFIL32 subdirectory.

Note   All other Setup Toolkit files are common to both 16-bit and 32-bit versions of Visual Basic and are located in the \VB\SETUPKIT\SETUP1 subdirectory.


See Also

Creating Distribution Media with the Setup Toolkit

Files You Are Allowed to Distribute

Files You Need to Distribute

Setup Toolkit Files


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 sell it commercially, you will need to write or use a setup program that installs the application on the user's machine.

The Visual Basic Setup Toolkit provides the tools you need to write setup programs using Visual Basic.  Most of the tools you need 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.

Pre-install files that you specify.

Use the version-stamping resources in Microsoft Windows to determine whether a file should be copied to the user's machine.

Install files in the appropriate Windows directories (\WINDOWS, \WINDOWS\SYSTEM, \WINDOWS\SYSTEM32).

Install Visual Basic Remote OLE Automation OLE servers on client and server sides.

Remove the application once it has been installed (32-Bit versions only).

Remove Remote OLE Automation components (32-Bit Enterprise Edition only).

Create Windows Program Manager groups and icons with Windows NT or 3.1x, or create Start menu links with Windows 95.


See Also

Creating Distribution Media with the Setup Toolkit

How to Use the Setup Toolkit

The Setup Wizard vs. the Setup Toolkit


Setup Toolkit Files

See Also

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:

Filename	Description
SETUP.EXE	The pre-installation program (sometimes referred to as a bootstrap program) that your user runs to install your application.  SETUP.EXE installs VER.DLL and all the files listed in the [BOOTSTRAP] section of SETUP.LST, and then invokes your custom setup program (SETUP1.EXE, or whatever filename you specify) to install your application.  You can rename this file.
SETUP1.VBP	A sample setup program used to install any Visual Basic application on a user's machine, and which generates executable files.
SETUP.LST	A text file that lists all the files to be installed on your user's machine, including the disk on which they reside, where they will be installed, whether and how they are to be registered in the system registry, and so forth.  SETUP.LST is required by SETUP.EXE, and each line contains installation information for a single file.  SETUP.LST is created automatically by the SetupWizard.
SETUP1.EXE (16-bit) SETUP132.EXE (32-bit)	A Visual Basic application that you customize.  These are the executable files that are generated by the sample setup program SETUP1.VBP.  Use these source files as a template for creating your own setup program.  You can rename these files but the new names must be reflected in SETUP.LST.
SETUP1.BAS	A collection of Visual Basic functions used in SETUP1.VBP to perform the tasks required by the setup program.
VER.DLL	A DLL that calls LZEXPAND.DLL, which copies and decompresses files.  VER.DLL can also detect the version of a file that has a Microsoft Windows version stamp.  You only need to distribute VER.DLL with 16-bit Visual Basic applications.
STKIT416.DLL (16-bit) STKIT432.DLL (32-bit)	A library that contains various functions used in the setup program.
ST4UNST.EXE (32-bit)	Application removal Uninstall utility for use with the Visual Basic Setup Toolkit.
CLIREG16.EXE (16-bit Enterprise Edition only)	16-bit Remote OLE Automation Client registration utility.
CLIREG32.EXE (32-bit Enterprise Edition only)	32-bit Remote OLE Automation Client registration utility.


See Also

16-Bit and 32-Bit Setup Files

Creating Distribution Media with the Setup Toolkit

Files You Are Allowed to Distribute

Files You Need to Distribute


How to Use the Setup Toolkit

See Also

You use the Setup Toolkit to create a setup program for your application by following these steps.  When you finish this procedure, you'll have a set of distribution disks or a network directory from which a user can install your application.

To create distribution media for your application

1.	Determine the files you need to distribute.

2.	Write your setup program.

3.	Compress the appropriate files.

4.	Determine the layout of your distribution disks (that is, which files go on which disks, if you are using disks).

5.	Determine where to install the files on the user's machine.

6.	Modify SETUP.LST to include all the files on your list.

7.	Create your distribution media.

8.	Test your setup program.


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Files You Need to Distribute

See Also

Before creating a setup program, you need to determine which files will be included in the release.  Before it can run, the setup program requires a set of files, referred to here as bootstrap files, along with all of the files specific to your application.  In addition to an executable file (.EXE), your application may require data files, custom controls, or other files such as DLLs and initialization files (.INI).  All of the bootstrap files your setup program needs are listed in the sample SETUP.LST file, as well as in SWDEPEND.INI.  Some of the additional files your application may require are listed in the following table:

Filename	Description

appname.EXE	Your application's .EXE file.

appname.DAT	(Optional) Any data files you created for your application.

appname.TXT	(Optional) Any text files you created for your application.

<control>.OCX

<control>.VBX	(Optional) Any custom controls required by your application.

<dependency>.DLL

<dependency>.EXE	(Optional) Any dependency files that your application requires, as listed in SWDEPEND.INI.

<olecontrol>.VBR

<olecontrol>.TLB	Remote Support files.
Type Library files.

Note   If you plan to distribute your application without using the SetupWizard and Setup Toolkit provided by Visual Basic, be sure that the controls and references (and their dependent files) used in your application are installed on the user's machine and registered in the system registry.  You can register files as part of your setup script, or you can ask users to do this manually.  The file dependencies and references included with Visual Basic are listed in the SWDEPEND.INI file, located in the \WINDOWS directory.  The SWDEPEND.TXT file describes the format of this file.

Visual Basic does not include custom controls, objects linked or embedded from other applications, or DLLs in your application's .EXE file.  If your application uses any of these file types, you must include the appropriate .OCX, .VBX, .EXE, and/or .DLL files on the distribution media.

Dependency Files

Depending on the operations your application performs and the custom controls it uses, you may also need to distribute separate libraries containing the objects and add-ins used in your application.  These other files are called dependencies and are identified in SWDEPEND.INI, which is in the \WINDOWS directory.  SWDEPEND.INI is a text file you can open with Microsoft Word, Microsoft Notepad, or any other text editor.

To determine which additional file(s) your application needs, check the list of files that appears under each section in SWDEPEND.INI.

Caution   If you are developing an application that requires Btrieve, you must have a licensing agreement with Btrieve Technologies to distribute 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 (BTRV200.DLL).


See Also

16-Bit and 32-Bit Setup Files

Creating the Distribution Media

Files You Are Allowed to Distribute

Setup Toolkit Files


Modifying SETUP.LST

See Also

SETUP.LST is a text file that lists all the files to be installed on the user's machine.  For 16-bit versions, a sample of this file is located in the \SETUPKIT\KITFILES subdirectory of the main Visual Basic directory, and for 32-bit versions, this file is listed in the \SETUPKIT\KITFIL32 subdirectory of the main Visual Basic directory.  SETUP.LST contains three sections: [BOOTSTRAP], [FILES], and [SETUP].

Modifying the [BOOTSTRAP] Section of SETUP.LST

Modifying the [FILES] Section of SETUP.LST

Modifying the [SETUP] Section of SETUP.LST

Formatting File Lists in [BOOTSTRAP] and [FILES]


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Modifying the [BOOTSTRAP] Section of SETUP.LST

See Also

The [BOOTSTRAP] section lists all the bootstrap files that must be loaded on the user's machine before your application and dependency files can be loaded.  These "pre-install" files include the core files required to run any Visual Basic application, as well as SETUP1.EXE (for 16-bit versions) or SETUP132.EXE (for 32-bit versions).  These files are installed by SETUP.EXE.

Note   The files SETUP.EXE, SETUP.LST, and VER.DLL must not be compressed.  You don't need to distribute VER.DLL with 32-bit Visual Basic applications.


See Also

Formatting File Lists in [BOOTSTRAP] and [FILES]

Modifying the [FILES] Section of SETUP.LST

Modifying the [SETUP] Section of SETUP.LST


Modifying the [FILES] Section of SETUP.LST

See Also

The [FILES] section contains all of the other files required by your application, such as your .EXE file, data, text, initialization files, dependency files, and so forth.  You may compress these files.  SETUP1.EXE (for 16-bit versions) and SETUP132.EXE (for 32-bit versions) continue the installation by copying the files listed in this section to the user's machine.


See Also

Formatting File Lists in [BOOTSTRAP] and [FILES]

Modifying the [BOOTSTRAP] Section of SETUP.LST

Modifying the [SETUP] Section of SETUP.LST


Formatting File Lists in [BOOTSTRAP] and [FILES]

See Also

Each file listed in the [BOOTSTRAP] and [FILES] sections of SETUP.LST must be described in the following format:

Filex=y,[SPLIT],file,install,path,register,shared,date,size[,version]

File is a keyword that must appear at the beginning of each file description line.

X is a sequence number, starting at 1 in each section.  The numbering sequence must be in order, and it can't skip any values.

Y is the number of the disk on which this file will be distributed.  If you are distributing to a network server or CD-ROM, this number is always 1.

SPLIT is an optional flag, indicating that this file isn't the last part of a segmented file.  For subsequent filenames that are part of this same file, don't repeat the fields following install.  Don't use the SPLIT keyword in the last piece of the same file.  A segmented file might be represented like this:

File10=2,SPLIT,GAZORNEN.DL1,GAZORNEN.DLL,$(WinSysPath),,,4/27/94, 1151756

File11=3,SPLIT,GAZORNEN.DL2,GAZORNEN.DLL

File12=4,SPLIT,GAZORNEN.DL3,GAZORNEN.DLL

File13=5,,GAZORNEN.DL4,GAZORNEN.DLL

File is the name of the file as it is distributed.

Install is the name of the file that is used during installation.  Usually, this is the same as file.  In some situations, the filename may be different, such as when you create the media using compressed files, where the last character of the filename extension is an underscore, and you want to install the file (after decompression) with the original character replacing the underscore.

Path is either an actual path or, preferably, a macro indicating a path specified by the user.  The following tables list the macros that can be used in the installation.

Macro	Description

$(WinSysPath)	Installs a file in the \WINDOWS\SYSTEM subdirectory.

$(WinPath)	Installs a file in the \WINDOWS directory.

$(AppPath)	Installs a file in the application directory specified by the user, or the DefaultDir value specified in the [SETUP] section.

$(AppPath)\SAMPLES	Installs a file in the \SAMPLES subdirectory below the application directory.

c:\path	Installs a file in the directory identified by path (not recommended).

$(CommonFiles)	The common directory to which shared files will be installed:
C:\PROGRAM FILES\COMMON FILES\ (Windows 95).
C:\WINDOWS\OLESVR (Window NT, Windows for Workgroups)

$(ProgramFiles)	The initial directory to which the application will be installed:
C:\PROGRAM FILES (Windows 95)
C:\ (Windows NT, Windows for Workgroups)

$(CommonFilesSys)	Installs a file in the specified directory:

$(CommonFiles)\System (Windows 95)
 \WINDOWS\SYSTEM (Windows NT, Windows for Workgroups)

Note   Because the setup program installs files in the \WINDOWS\SYSTEM directory, the 32-bit Setup Toolkit should not be used to install a 16-bit application.

In the [BOOTSTRAP] section, no file may be installed using $(AppPath).

Register is a key that indicates how the file is to be included in the user's system registry.  The four possible keys are listed in the following table.

Key	Description

(no key)	This file does not need to be registered on the user's machine.

$(DLLSelfRegister)	Use this key if the file is a self-registering DLL, .OCX custom control, or any other file with self-registering information.

$(EXESelfRegister)	Use this key if the file is a self-registering .EXE file, such as an OLE server created in Visual Basic.

$(Remote)	This key indicates that the file is a Remote Support file OLE Automation Remote OLE server registration file (.VBR).

appname.REG	Use this key for any component you distribute that needs to be registered but that does not provide self-registration.  This key contains information that updates the system registry.  The appname argument is the root filename used as an argument to REGEDIT.EXE or REGEDIT32.EXE.

Note   Using the <appname>.REG key for distributing components is not the recommended method of getting registration information into the 32-bit system registry.  To update the system registry correctly, use the RegCreateKey, RegSetNumericValue, RegSetStringValue, RegOpenKey, and RegCloseKey functions in SETUP1.VBP and recompile SETUP132.EXE.  Refer to commented code in SETUP1.VBP.

Remote# is a line written to SETUP.LST using information from the Remote Server Details dialog at step 4 of the SetupWizard.  This line contains the command line information used by the Client Registration utility to register the Remote OLE Automation server.  This information consists of the server address, network protocol, and authentication information, separated by commas.  The # corresponds to the File# that contains the $(Remote) key.  Following is an example of the Remote# implementation.

File2=1,,RemSvr1.VB_,RemSvr1.VBR,$(CommonFiles)\OLESVR,$(Remote),$(Shared),4/10/1995,1147

Remote2="Schweizer","ncacn_ip_tcp",1

File3=1,,RemSvr2.VB_,RemSvr2.VBR,$(CommonFiles)\OLESVR,$(Remote),$(Shared),4/10/1995,1147

Remote3=,,1

$(Shared) is a keyword automatically added to the list entry of any file installed to \WINDOWS, \WINDOWS\SYSTEM, or $(CommonFiles) of the Common Files directory (\WINDOWS or any subdirectory of \WINDOWS with Windows NT and Windows for Workgroups, \PROGRAM FILES\COMMON FILES with Windows 95).  This keyword can be either $(Shared) indicating that it is a shared file and is registered in the system registry, or blank indicating that it is a private file.

Date and size are the same as the last date modified and file size as it would appear in the File Manager.  This information helps you to verify that you have the correct versions of the files on the setup disks.  Size is used by SETUP1.EXE (16-bit) or SETUP132.EXE (32-bit) to calculate how much disk space your application requires on the user's machine.

Version is an optional internal version number of the file.  You can determine this number by clicking the File Details button on Step 7 of the SetupWizard.  Note that this isn't necessarily the same number as the display version number you see by checking the File Properties in the File Manager.


See Also

Modifying the [BOOTSTRAP] Section of SETUP.LST

Modifying the [FILES] Section of SETUP.LST

Modifying the [SETUP] Section of SETUP.LST


Modifying the [SETUP] Section of SETUP.LST

See Also

The third section of the SETUP.LST file, [SETUP], is simply a list of information used by other parts of the setup program.  The following table lists the information contained in the [SETUP] section.

Component	Description

Title	The name of the application that appears in the splash screen during installation.

DefaultDir	The directory into which the application is installed, unless the user enters a different destination directory during the setup program.

Setup	The name of the setup program file, normally SETUP1.EXE.  If you change the name of this file, be sure to insert the new name here.

Btrieve	Should be set to a nonzero value if you include Btrieve drivers in the distribution files.

AppEXE	Should be set to the name of your application, such as MYAPP.EXE.

You can give your setup program any name except SETUP.EXE, which is the name of the pre-installation program.  For example, you can name your setup program SETUP1.EXE, SETLOAN.EXE, or MYSETUP.EXE.

In some cases, you may want to access DLLs or use custom controls in your setup program that are not already used by SETUP1.VBP.  If so, you must include the names of these files in the [BOOTSTRAP] section of SETUP.LST.


See Also

Formatting File Lists in [BOOTSTRAP] and [FILES]

Modifying the [BOOTSTRAP] Section of SETUP.LST

Modifying the [FILES] Section of SETUP.LST


Compressing the Setup Files

See Also

Once you have determined which files need to be included on the distribution media, you may discover that all of the files can't fit on a single disk.  By compressing the files on your distribution disks, you may be able to reduce the number of disks required to distribute your application.

The Setup Toolkit provides a utility that allows you to compress files.  It is called COMPRESS.EXE and is located in the \SETUPKIT subdirectory of the main Visual Basic directory.  COMPRESS.EXE is an MS-DOS [image] based utility, not a Microsoft Windows [image] based application.

To compress a file

At the command-line prompt, type:

compress -r filename

The -r switch replaces the last character of the compressed file's filename extension 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_.  When decompressed, the file is renamed as specified by the file entry in SETUP.LST.  By convention, this would usually be LOAN.EXE.  However, you can rename the expanded file.

You can compress any file and as many files as you want, except VER.DLL (16-bit versions only), SETUP.EXE, and SETUP.LST.  VER.DLL recognizes when a file has been compressed and copies all files to the user's machine correctly when you use version 2.0 of COMPRESS.EXE, which comes with the Setup Toolkit.


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Layout of the Distribution Disks

See Also

If you are distributing your application on disks, know the name of each file in your application and the distribution disk on which it resides before you write your setup program.

The first distribution disk must contain the following files:

SETUP.EXE

SETUP.LST

VER.DLL (16-bit Visual Basic applications only)

ST4UNST.EX_ (32-bit Visual Basic applications only)

These three files won't fill a single disk, so you can include other files.  The remaining bootstrap files must be installed before your application files are installed.  If these files take up more room than a single disk, determine how to assign the rest of the bootstrap files to the first and subsequent disks.

Following the last bootstrap file, you can start laying out your program files.  The program files can be loaded in any order; however, remember that all of the bootstrap files must be installed before any of your program files.

By calculating the size of the remaining files, you can determine which files each disk should contain.

Note   Unlike the SetupWizard, the Setup Toolkit does not automatically split a file between disks.


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Where to Install Files on the User's Machine

See Also

Before writing your setup program, you must determine where on the user's machine you want to install each file.  The files that are required by your application can be divided into several categories:

Program files

Initialization files

Operating system components

Shared application components

Program Files

These files are essential and are useful only in the context of your application.  For example, your application's .EXE file and any data files that your application may require are considered program files.  Install program files in the application directory.  The user is prompted for this directory during setup.  See the sample code for this in SETUP1.VBP.

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 machine by calling the GetWindowsDirectory Windows API function.  The code in SETUP1.VBP shows how to call this function.

Note   For 32-bit applications, use the system registry to store application-specific information, not .INI files.

Operating System Components

These files are usually 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 OLE2.DLL or SHELL.DLL. Install these files in the \WINDOWS\SYSTEM directory.  To determine the name of this directory, call the GetSystemDirectory Windows API function.  The code in SETUP1.VBP shows how to call this function.

Caution   When installing a file on the user's machine, it is imperative that you don't copy an older version of the file over a new version.  The CopyFile function in SETUP1.BAS uses the VerInstallFile API function to copy files to the user's machine.  VerInstallFile only overwrites a file that has an older revision number than the one being copied.

Shared Application Components

Application components can be shared by more than one application.  For example, several different vendors may ship applications that use the same custom control.  By installing .OCX, .VBX, and .DLL files in the \WINDOWS\SYSTEM subdirectory, you can ensure that all applications use the most current files.


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Writing Your Setup Program

See Also

The quickest way to write your setup program is to modify the SETUP.LST file included with the Setup Toolkit, so that it copies the files for your application instead of those for LOAN.EXE.  The sample setup program SETUP1.VBP is located in the \SETUPKIT\SETUP1 subdirectory of the main Visual Basic directory.  You can modify the sample setup programs to install any of your Visual Basic applications.  The sample setup program installs the sample application LOAN.EXE, which is located in the \SAMPLES\GRID subdirectory of the main Visual Basic directory.

LOAN.EXE is a small sample application that uses the Grid custom control.  To run correctly, LOAN.EXE requires that GRID16.OCX be properly installed on the user's machine.  This is a typical setup scenario for applications that use custom controls.

Customizing the Setup Procedure

To add other user prompts and other events to the setup sequence, you can modify SETUP1.VBP.  You can write code in the setup program just as you would in any other Visual Basic program.  Furthermore, a number of function calls are available that are especially useful in setup routines.

CalcDiskSpace and CopySection Statements

These statements install a block of contiguous files named in SETUP.LST under the section name represented in the string argument to the statement.  You can use the following code in the sample setup program SETUP1.VBP to calculate the disk space required for all the files listed under [FILES] in SETUP.LST, and then install them if there is sufficient disk space.

CalcDiskSpace "Files"

CopySection "Files"

You can use additional statements to install optional blocks of files, as described in Creating Installation Options.


See Also

Creating Distribution Media with the Setup Toolkit

Creating Installation Options

Setup Toolkit Overview


Creating the Distribution Media

See Also

Before you copy files to the distribution media, it's a good idea to label the media.  For example, if you are distributing your application on disks, attach a label on the first disk that reads Disk1: Setup Disk I, and then insert this disk in drive A:.

Windows NT or Windows for Workgroups:

In the File Manager, select drive A:.

Select the Disk menu, and then choose Label Disk.

Type setup and press Enter.

Windows 95:

From the Windows Explorer, select drive A:.

Choose the File menu and scroll down to Properties.

Type setup in the Label text box and press Enter.

This label provides all the instructions your user needs to install your application.  You can label the remaining media similarly.  For example:

Disk2: MyApp

Now you are ready to copy your files to the appropriate distribution media.

To create distribution disks

1.	(For 16-bit applications only) Rename VER.DLL to VER.DL_.  For example:

rename a:ver.dll a:ver.dl_

You must change the VER.DLL filename extension to .DL_ so that Microsoft Windows does not try to use it while the setup disk is in the disk drive.

2.	Copy these files onto the first disk:

SETUP.EXE

SETUP.LST

VER.DL_ (16-bit applications only)

3.	Copy the remaining files as specified by your disk layout.


See Also

Creating a Network Server Distribution Directory

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Creating a Network Server Distribution Directory

See Also

To distribute your application over a network, copy all the files into a single directory on the network server.  To distribute the application on CD-ROM, copy the files to a single directory from which the CD-ROM generation system can read them.  In either case, be sure there are no other files in the destination directory before copying your application files.


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Testing Your Setup Program

See Also

After you create the distribution disks or a network directory containing the distribution files, you should test your setup program.  Be sure to test your setup program on a machine that does not have Visual Basic installed, or any of the custom controls required by your application.  Be sure to test your setup program on all operating system platforms on which your setup program will be run.

To test your setup program using distribution disks

Windows NT and Windows for Workgroups:

1.	Insert the first disk in drive A.

2.	In the Windows Program Manager, choose Run from the File menu and type: a:setup

Windows 95:

1.	Insert the first disk in drive A.

2.	From the Start Menu, choose Settings and then choose Control Panel.

3.	From the Control Panel, double-click Add/Remove Programs.

4.	Select the Install/Uninstall tab, choose Install, and click Next.

5.	When the Run Installation Program dialog box displays the command line containing SETUP.EXE, choose Finish to install the program.  If Windows 95 cannot find the installation program, you may have to choose the Browse button and search for the installation program.

If your application does not install properly, make sure the layout of the distribution disks matches the code in your setup program.

To test your setup program using network distribution

1.	From another computer on the same network as the distribution server, use the Microsoft Windows File Manager (Windows NT or Windows for Workgroups) or the Microsoft Window 95 Explorer (Windows 95) to connect to the server and directory containing your distribution files.

2.	In the distribution directory, double-click the SETUP.EXE file.  If your application does not install properly, make sure the layout of the distribution disks matches the code in your setup program.

As a final test, execute the installed program to be sure that, once installed, it behaves as you expect it to.


See Also

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


Creating Installation Options

See Also

You can use the Setup Toolkit and the SetupWizard together to add dialog boxes to the installation program, prompting the user to specify whether to install optional features in your application.  For example, you may have an online Help file that some users would rather not install.  You can add as many installation options as you want.

To add an installation option to your setup program

1.	Edit the code in SETUP1.FRM located in the \SETUPKIT\SETUP1 subdirectory of the main Visual Basic directory.  Immediately after the code block that calls "ShowBeginForm," add code like the following:

Dim LoadHelp As Integer

LoadHelp = MsgBox ("Do you want to install Help? ", vbYesNo)

If LoadHelp = vbYes Then

CalcDiskSpace "Help"

EndIf

.

.     ' Block of code containing CopySection strINI_Files

.

If LoadHelp = vbYes Then

CopySection "Help"

EndIf

2.	Close SETUP1.FRM, save the form and the project, and create an .EXE file.

3.	Run the SetupWizard.  At Step 7, after you've confirmed all of the file dependencies, add the names of all the files you want to install if your user answers "Yes" to this dialog box.

4.	Once you are done with the SetupWizard, generate the distribution media.

5.	Insert Disk1 into a drive and open the SETUP.LST file.  Cut and paste the optional file(s) from the [FILES] section to a new section.  Put this new section below the [FILES] section and give it a new section title that corresponds to the string argument (for instance, [HELP]) that you used in the CopySection statement.

[HELP]

File1=5,SPLIT,MyApp.HL1,MyApp.HLP,$(AppPath),,,4/22/94,2946967

File2=6,SPLIT,MyApp.HL2,MyApp.HLP

File3=7,,MyApp.HL3,MyApp.HLP

When the user runs the installation program, SETUP.EXE copies all the [BOOTSTRAP] files to the user's machine, and then SETUP1.EXE prompts the user to indicate whether to install the Help files.  If the user chooses Yes, the CalcDiskSpace statement determines whether there is sufficient disk space on the user's machine for the Help files.

The SETUP1.EXE program then installs all of the files listed under the [FILES] section in SETUP.LST.

Next, the program tests the LoadHelp flag again.  If users choose to install the Help files, SETUP1.EXE then executes the CopySection statement for the Help files and installs the files listed in the [HELP] section of SETUP.LST.


See Also

Creating a Setup Disk for ODBC Applications (Professional and Enterprise Editions Only)

Creating Distribution Media with the Setup Toolkit

Setup Toolkit Overview


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 (.OCX or .VBX), or bitmaps (.BMP).

You can legally distribute sample application files (found in the \SAMPLES subdirectory) and any files that were originally copied to the \ICONS subdirectory of the main Visual Basic directory when you first installed Visual Basic version 4.0 on your system.

Other files you may freely distribute are identified in the file SWDEPEND.INI.  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.

Professional and Enterprise Editions

If you have purchased the Professional or Enterprise Edition of Visual Basic, you can also distribute any files originally copied to the \BITMAPS, \METAFILE, and \ODBC subdirectories of the main Visual Basic directory when you first installed Visual Basic version 4.0 on your system.

Note   You may also be able to distribute other custom controls, .EXE files, and DLLs that you have purchased. Consult the manufacturer's license agreement for each of the files you plan to distribute to determine whether you have the right to distribute the file with your application.


See Also

16-Bit and 32-Bit Setup Files

Creating the Distribution Media

Files You Need to Distribute

Setup Toolkit Files


Creating a Setup Disk for ODBC Applications (Professional and Enterprise Editions 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 install 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 (for 16-bit applications) or \ODBC32 (for 32-bit applications) subdirectory of the main Visual Basic directory to a disk or network directory.

2.	After installing your application on the user's machine, run SETUP.EXE on the ODBC setup disk or network directory.  Either use the Shell function to run ODBC SETUP.EXE from your setup program, or label the ODBC setup disk with a title such as "ODBC Setup Program.  Run SETUP.EXE after installing the application."

Once you have placed the ODBC files on a disk, test the ODBC setup disk on a machine that does not have ODBC files.

Note   To install ODBC on a user's machine, you must use the setup program provided in the \ODBC or \ODBC32 subdirectory of the main Visual Basic directory.  Some of the ODBC files are compressed, and the setup program must decompress them to install them correctly.


See Also

Creating Distribution Media with the Setup Toolkit

Creating Installation Options

Setup Toolkit Overview


Including or Excluding Dependency Files

See Also

Some of the files included in the Dependency Of Frame in SetupWizard Step 7 do not need to be included with all applications.  A partial list of those files and their function follows; if you do not need this functionality, then you can exclude the file.  If you choose to exclude a file, you should test your application's functionality before releasing your setup disks for general distribution.

File	Function

MSWNG300.DLL	DAO 3.0 replication methods.

CTL3DV2.DLL (16-bit)	3D effects for Visual Basic Inputboxes, message boxes, and error messages for 16-bit Visual Basic applications; this file is not needed if the application is running with Windows 95.

CTL3D32.DLL (32-bit)	3D effects for Visual Basic Inputboxes, message boxes, and error messages for 32-bit Visual Basic applications; this file is not needed if the application is running with Windows 95.


See Also

SWDEPEND.INI

SWDEPEND.TXT


SWDEPEND.TXT

See Also

This is an explanatory text file for the SWDEPEND.INI file.  It describes the contents and layout of the SWDEPEND.INI file, and also describes which Visual Basic files can be freely distributed with your application.  This file is located in the \SETUPKIT directory.


See Also

Files You Are Allowed to Distribute

Files You Need to Distribute

Including or Excluding Dependency Files

SWDEPEND.INI


SWDEPEND.INI

See Also

This file contains the list of files that Visual Basic depends on for certain functionality.  SetupWizard reads this file to gather information on other file dependencies, special file attributes, and the destination of installation files when building setup disks.  This file is located in the \WINDOWS directory.


See Also

Files You Are Allowed to Distribute

Files You Need to Distribute

Including or Excluding Dependency Files

SWDEPEND.TXT


Client Registration Utility

The Client Registration utility is used by Visual Basic Setup Toolkit setup applications to register an OLE Automation server for remote execution.  This utility is automatically included in SETUP.LST by the SetupWizard when the setup script specifies a remote OLE Automation server.  The setup application uses CliReg to register the remote OLE Automation server when setup is run on the end-user's machine.  The Client Registration utility uses the Remote Support (.VBR) and Type Library (.TLB) files that Visual Basic produces when it makes the OLE server's .EXE file.  To create these files for your Remote OLE Automation server, from the File menu, choose Make EXE File, select Options, and check the Remote Server Support Files checkbox.

Syntax

CLIREG[32][.EXE] vbrfile -s {s} | -p {p} | -a {a} | -t {t} | -u | -q | -l | -nologo | -[h | ?]

Option	Description

-s {s}	Specify network address {s}.

-p {p}	Specify network protocol {p}.

-a {a}	Specify security authentication level {a}; valid range is from 0 to 6.

-t {t}	Specify typelib file {t}.

-u	Quiet mode: no information dialogs or error messages.

-l	Log error information to file "CLIREG.LOG".

-nologo	Do not display copyright information.

-[h | ?]	Display the Help dialog box that presents command line options.

For more information on using the CliReg utility, refer to Chapter 3, "Client/Server Tools in the Enterprise Edition," of the book Building Client/Server Applications with Visual Basic in your Visual Basic Enterprise Edition documentation.


Application Removal (32-bit only)

The Application Removal utility (ST4UNST.EXE) uses the setup log generated by Setup (bootstrap) and SETUP132.EXE to remove an application installation.  If you generate your own SETUP132.EXE, these become relevant command-line options that are passed to ST4UNST.EXE by SETUP132.EXE, by the Bootstrapper, or are written as a command line parameter for an Windows NT icon.

Syntax

ST4UNST[.EXE] -n | -e | -e1 | -e2 | -e3 | -f | -w processid

Option	Description

-n	Full path to application setup log file.  This is the only required parameter.

-e 1	Started as result of a fatal error in Setup or Setup1.  Under this condition, the error message "A serious setup error has occurred - removing temporary setup files" will be displayed and the application removal utility asks the user whether or not to delete the log file.

-e 2	Started as result of a non-fatal error in Setup or Setup1User chose to abort the installation.  The error message "A serious setup error has occurred - removing temporary setup files" will be displayed and the application removal utility asks the user whether or not to delete the log file.

-e 3	The user pressed the cancel button without being prompted.  The message "Removing temporary files" will be displayed and the log file will be deleted.

-f	"Force" installation removal.  User is not asked for confirmation before beginning the application removal process.  The user will still be asked about removing shared files.  This option is normally given when -e is present.

-w (processid)	Application removal utility waits until the process specified by the process ID (processid) is completed before attempting to remove the application.  Useful if SETUP132.EXE called the application removal utility, and the scenario requires that SETUP132.EXE complete and terminate before removing installation.


Application Removal Failure Scenarios

The Application Removal utility depends upon an accurate log file and an accurate system registry to perform its function.  The following are a few of the possible scenarios that will cause the Application Removal utility to fail or to work incorrectly:

1.	The end user copies shared files manually (i.e., without updating reference counting).

2.	The end user deletes installed files or an application directory rather than using the application removal utility.  This creates two problems:

Deletes the logfile, so application removal is later impossible,

Makes it impossible to remove system registry entries from program files, .DLLs, or .OCXs in the application directory, because they must be run for them to remove their system registry entries).

3.	A setup program for a 16-bit or non-Windows 95-compliant application installs the same shared files that are also installed by your Windows 95-compliant application.

4.	A shared file is installed into a different directory than the one in which it already exists on the hard drive.

5.	A setup program is created with the SetupWizard and used for the installation of a Visual Basic application, with the deployment mode set in a particular  way.  Later, a different setup program is created and used for the same application, but with a different deployment mode.

6.	You create a setup program with the SetupWizard, with the deployment model set for "install as stand-alone application," and run the setup.  Later, another setup program is created for a different Visual Basic application, and the first application is added to this setup program as a component (i.e., using Add OLE Servers or Add Files buttons).  If it is possible that the end user might install a particular Visual Basic OLE Automation server as a component in the setup program of another application, you must use deployment set to "install as shared component."

7.	The end user installs the same Visual Basic application in two different directories.  Not only will the first installation no longer work, but the Application Removal scenarios will clash.  The end user should always remove the first installation before installing an application in a different directory.

8.	User deletion of application setup log.  Without the application setup log file, the Application Removal utility will have no installation information, and will fail.

Some of these scenarios could degrade the installed file-registry correspondence, cause the Application Removal utility to prematurely reach a zero-reference count for a particular file, and subsequently ask if this file could be deleted.  If a file is prematurely deleted, it could cause other applications to cease functioning or function incorrectly due to missing file dependencies, missing components, and so on.


Error message "Cannot start main setup program!"
SetupWizard Error message "Cannot start main setup program!"

This error message varies slightly between 16-bit and 32-bit versions of the SetupWizard.  The 16-bit SetupWizard will return the error message "Cannot start main setup program!  (WinExec() returned error code number)." The number indicates the returned error code; this number is in hexadecimal format.  Refer to the WinExec error codes in the Win31SDK.HLP (16-bit) for more information.

The 32-bit SetupWizard will return the error message "Cannot start main setup program!  (CreateProcess() returned error code number)."  The number indicates the returned error code; this number is in hexadecimal format.  Refer to the Win32 API error codes in the WinError.H file for more information.

This error message can result from several possible conditions.  Some of the more common conditions might be:

Problem	Solution

SETUP1.EXE has been corrupted.	Rebuild SETUP1.EXE.

Support files are missing or corrupted.	Check SWDEPEND.INI for bootstrap files and check them for integrity.

Check to see that SETUP132.EXE is correctly referenced in SETUP.LST.

Installation disks are corrupted.	Rebuild installation disks.


ActiveProject Property (Add-In)

See Also	Applies To

Returns the ProjectTemplate object representing the active project.

Syntax

object.ActiveProject

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use the ActiveProject property to determine the active project.  Because the current version of Visual Basic supports only one active project at a time, this property represents the open project.  You can also use the ActiveProject property to:

Access the current ActiveForm object.

Add new forms or other elements to the project.

Determine the currently selected components.


See Also

ProjectTemplate Object (Add-In)

LoadProject Method


ActiveProject Property (Add-In) Applies To

Application Object (Add-In)


Add Method (Add-In)

See Also	Applies To

ControlTemplates collection [image] adds a new control to the form.

MenuItems collection [image] adds a MenuLine object to the collection.

Doesn't support named arguments.

Syntax

object.Add (classname [, container]) As ControlTemplate

object.Add (caption) As MenuLine

The Add method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

classname	Required.  Used with ControlTemplates.  A string expression specifying the name of the class of control you want to add.

container	Optional.  Used with ControlTemplates.  An object expression specifying the container for the control you want to add.

caption	Required.  Used with MenuItems.  A string expression specifying the caption for a new MenuLine object.  The value of caption must include an ampersand (&) before the access key.

Remarks

For ControlTemplates, a reference to the class of the control must already exist in the active project.  This method returns a ControlTemplate object representing the new control.

For MenuItems, the Add method returns a new MenuLine object.

To include an ampersand in a command without creating an access key, use two ampersands (&&).  When you do this, a single ampersand is displayed on the command and no characters are underlined.  The argument caption cannot be "-", because add-ins cannot add a separator bar to the menu.


See Also

AddMenu Method (Add-In)

AddReference Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxTypelib Method (Add-In)

AddToolboxVBX Method (Add-In)

ControlTemplate Object, ControlTemplates Collection (Add-In)

MenuLine Object (Add-In)

Remove Method (Add-In)


Add Method (Add-In) Applies To

ControlTemplate Object, ControlTemplates Collection (Add-In)

MenuItems Collection (Add-In)


AddFile Method (Add-In)

See Also	Applies To

Adds the file containing a form or module to the active project from a file.  Doesn't support named arguments.

Syntax

object.AddFile (filename) As String

The AddFile method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filename	Required.  A string expression specifying the filename of the form or module you want to add to the project.  If the file isn't found and a pathname is not specified, the directories searched by the Windows OpenFile function are searched.

Remarks

The AddFile method determines what type of file is added and returns a string that indicates the type of file added (either "Form", "Module", or "Class").

Note   Successfully calling this method invokes the corresponding events of the FileControl object.


See Also

FileControl Object (Add-In)

RemoveComponent Method (Add-In)


AddFile Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AddFormTemplate Method (Add-In)

See Also	Applies To

Adds a new blank form to the project.  Doesn't support named arguments.

Syntax

object.AddFormTemplate

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The Form object created by the AddFormTemplate method becomes the active Form object.  The default name assigned to the new Form object is the same one given when you choose Insert from the Form menu.  This method returns a FormTemplate object representing the new form.


See Also

AddFile Method (Add-In)

AddMDIFormTemplate Method (Add-In)

FormTemplate Object (Add-In)

RemoveComponent Method (Add-In)


AddFormTemplate Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AddInMenu Property (Add-In)

See Also	Applies To

Returns the SubMenu object representing the Add-Ins menu on the Visual Basic menu bar.

Syntax

object.AddInMenu

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use the AddInMenu property to add menus and commands to the Add-Ins menu.  The SubMenu object returned by this property has the properties and methods of any other SubMenu object, except that the Parent property of the SubMenu object returned by the AddInMenu is set to a null value.


See Also

SubMenu Object (Add-In)


AddInMenu Property (Add-In) Applies To

Application Object (Add-In)


AddMDIFormTemplate Method (Add-In)

See Also	Applies To

Adds a new MDIForm object to the project.  Doesn't support named arguments.

Syntax

object.AddMDIFormTemplate

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The new MDIForm object becomes the active form.  Restrictions on the type of controls that you can add to the MDIForm object are still enforced.  Adding controls without an Align property for the MDIForm object causes an error.

The default name assigned to the new MDIForm object is the same one given when you choose MDIForm from the Insert menu.

Because only one MDIForm object may exist in a project, an error occurs if an MDIForm object already exists in the project when this method is called.  The AddMDIFormTemplate method returns a FormTemplate object representing the new MDIForm object.


See Also

AddFile Method (Add-In)

AddFormTemplate Method (Add-In)

FormTemplate Object (Add-In)

RemoveComponent Method (Add-In)


AddMDIFormTemplate Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AddMenu Method (Add-In)

See Also	Applies To

Adds a SubMenu object to a MenuItems collection.  Doesn't support named arguments.

Syntax

object.AddMenu caption

The AddMenu method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

caption	Required.  A string expression specifying the Caption property for the new menu; caption must include an ampersand (&) before the character to be defined as the access key.

Remarks

To specify an ampersand in a command without specifying an access key, use two ampersands (&&).


See Also

Add Method (Add-In)

Remove Method (Add-In)

SubMenu Object (Add-In)


AddMenu Method (Add-In) Applies To

MenuItems Collection (Add-In)


AddMenuTemplate Method (Add-In)

See Also	Applies To

Adds a SubMenu object to a Form object.  Doesn't support named arguments.

Syntax

object.AddMenuTemplate name, parent

The AddMenuTemplate method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

name	Required.  A string expression specifying the Name property for the new menu.

parent	Required.  The name of a ControlTemplate object representing the parent menu item that the new menu item becomes a child of; to add a menu to the menu bar of a form, set parent to Nothing.

Remarks

Menus on forms are accessed as ControlTemplate objects.  Menus are added to the end of existing menus; menus can't be inserted between two existing menus.  This method returns a ControlTemplate object representing the new menu.


See Also

ControlTemplate Object, ControlTemplates Collection (Add-In)


AddMenuTemplate Method (Add-In) Applies To

FormTemplate Object (Add-In)


AddReference Method (Add-In)

See Also	Applies To

Adds a reference to a specified type library in Visual Basic.  Doesn't support named arguments.

Syntax

object.AddReference guid, majorversion, minorversion, filename

The AddReference method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

guid	Optional.  A string expression specifying the globally unique identifier of the type library.  If guid is specified, majorversion must also be specified.

majorversion	Optional.  A short expression specifying the major version of the type library.

minorversion	Optional.  A short expression specifying the minor version of the type library.  If minorversion isn't specified, the most recent minorversion for the specified majorversion is used, if available.

filename	Optional.  A string expression specifying the filename of the specified type library to be added to Visual Basic.  A complete pathname can be used; if the file isn't found, the directories searched by the Windows OpenFile function are searched, even if a complete pathname is specified.

Remarks

If guid is specified but not found in the type library portion of the system registry or no guid is specified and filename is given, Visual Basic attempts to load the specified file, register the file in the system registry, and reference from the newly registered file.  If the guid isn't found in the type library portion of the system registry or isn't given, and the filename isn't found or isn't given, an error occurs.

Note   Calling this method puts the specified type library at the end of the list of references.  This is important because, if an incomplete object name is used (such as Sheet instead of Excel.Sheet), Visual Basic uses the first matching object it finds in the list of references, starting from the top of the list.


See Also

Add Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxTypelib Method (Add-In)

AddToolboxVBX Method (Add-In)


AddReference Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AddToolboxProgID Method (Add-In)

See Also	Applies To

Adds a compound document object to the Visual Basic toolbox.  Doesn't support named arguments.

Syntax

object.AddToolboxProgID progid, filename

The AddToolboxProgID method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

progid	Required.  A string expression specifying the programmatic identifier of the compound document object to add to the Visual Basic toolbox.  Either a version-independent or version-dependent progid can be used.  If a version-independent progid is specified, the most recent version is used.  If the compound document object has an associated type library, this type library is referenced as well.

filename	Optional.  String expression specifying the filename of the desired type library to be added to Visual Basic.  A complete pathname can be used; if the file isn't found, the directories searched by the Windows OpenFile function are searched, even if a complete pathname is specified.

Remarks

If progid isn't found and filename is specified, Visual Basic searches for a type library in the specified file, registers it in the system registry, and then attempts to add the newly registered object to the toolbox.  If the specified type library contains more than one object, all objects are placed into the toolbox.  If progid isn't found and filename isn't specified, an error occurs.


See Also

Add Method (Add-In)

AddReference Method (Add-In)

AddToolboxTypelib Method (Add-In)

AddToolboxVBX Method (Add-In)


AddToolboxProgID Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AddToolboxTypelib Method (Add-In)

See Also	Applies To

Specifies a reference to a type library and places the objects from the type library into the Visual Basic toolbox.  Doesn't support named arguments.

Syntax

object.AddToolboxTypelib guid, majorversion, minorversion, filename

The AddToolboxTypelib method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

guid	Required.  A string expression specifying the globally unique identifier of the object to be placed in the Visual Basic toolbox.

majorversion	Required.  A short expression specifying the major version of the object to be placed in the Visual Basic toolbox.

minorversion	Required.  A short expression specifying the minor version of the object to be placed in the Visual Basic toolbox.

filename	Optional.  A string expression specifying the filename of the type library to be referenced in Visual Basic.  A complete pathname can be used; if the file isn't found, the directories searched by the Windows OpenFile function are searched, even if a complete pathname is specified.

Remarks

If guid, majorversion, and minorversion aren't found and filename is specified, Visual Basic searches for a type library in the specified file, registers it in the system registry, and then attempts to add the newly registered object to the toolbox.  If the specified file contains more than one object, all objects are placed into the toolbox. If guid, majorversion, and minorversion aren't found and filename isn't specified, an error occurs.

Note   Calling this method puts the specified type library at the end of the list of references.  This is important, because, if an incomplete object name is used (such as Sheet instead of Excel.Sheet), Visual Basic uses the first matching object it finds in the list of references, starting from the top of the list.


See Also

Add Method (Add-In)

AddReference Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxVBX Method (Add-In)


AddToolboxTypelib Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AddToolboxVBX Method (Add-In)

See Also	Applies To

Adds a VBX control to the Visual Basic toolbox.  Doesn't support named arguments.

Syntax

object.AddToolboxVBX vbxfile

The AddToolboxVBX method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

vbxfile	Required.  A string expression specifying the filename of the VBX control to add to the Visual Basic toolbox.  A complete pathname can be used; if the file isn't found, the directories searched by the Windows OpenFile function are searched, even if a complete pathname is specified.

Remarks

If the specified file contains more than one VBX control, all VBX controls in the file are added to the toolbox.


See Also

Add Method (Add-In)

AddReference Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxTypelib Method (Add-In)


AddToolboxVBX Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


AfterAddFile Event (Add-In)

See Also	Applies To

Occurs after a form, class, or module file has been added to the current Visual Basic project.

Syntax

Sub AfterAddFile(filename As String)

The filename placeholder represents a string expression specifying the name of the file that was added.

Remarks

Visual Basic triggers this event only for files you can add using the Add File command in the File menu (that is, forms, classes, and modules).  If an .FRX file is associated with a form, this event is triggered twice [image] once for the .FRM file and once for the .FRX file.  When saving a form that produces an .FRX file for the first time, Visual Basic triggers this event for the .FRX file because it is also being added to the project.  This event is triggered in all the add-ins that are connected to the FileControl object.  The add-in can't stop the file from being added because the operation is complete; however, the add-in can log information about the event.


See Also

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

DoGetAddFileName Event (Add-In)


AfterAddFile Event (Add-In) Applies To

FileControl Object (Add-In)


AfterChangeFileName Event (Add-In)

See Also	Applies To

Occurs after a file in the current project has been renamed and saved or when an .EXE file has been created.

Syntax

Sub AfterChangeFileName(filetype As String, newname As String, oldname As String)

The AfterChangeFileName event syntax has these parts:

Part	Description

filetype 	A value or constant that specifies the component type of the file, as described in Settings.

newname 	A string expression containing the name given to the renamed file.

oldname 	A string expression containing the name of the file before it was renamed.

Settings

The values for filetype are:

Constant	Value	Description

vbextFileTypeForm	0	Form

vbextFileTypeModule	1	Module

vbextFileTypeClass	2	Class

vbextFileTypeProject	3	Project

vbextFileTypeExe	4	.EXE

vbextFileTypeFrx	5	.FRX

vbextFileTypeRes	6	.RES

Remarks

If an .FRX file is associated with a form, this event is triggered twice.  This event is triggered for all the add-ins that are connected to the FileControl object.  The add-in can't stop the file from being renamed because the operation is complete; however, the add-in can log information about the event, prompt the user to delete the original file, and so on.  A BeforeLoadFile event is subsequently triggered for the files that have been renamed.


See Also

BeforeLoadFile Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

DoGetNewFileName Event (Add-In)

RequestChangeFileName Event (Add-In)


AfterChangeFileName Event (Add-In) Applies To

FileControl Object (Add-In)


AfterClick Event (Add-In)

See Also	Applies To

Occurs when the Visual Basic user clicks the menu item associated with a MenuLine object.

Syntax

Sub AfterClick()

Remarks

This event is triggered for the object that was passed to the ConnectEvents method of the MenuLine object.  Once the object has been passed, every time the user clicks the menu item the AfterClick event is triggered.  Because there is no way to determine which menu item was clicked, there must be a separate object for each menu item.


See Also

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)


AfterClick Event (Add-In) Applies To

MenuLine Object (Add-In)


AfterCloseFile Event (Add-In)

See Also	Applies To

Occurs after a project has been closed, either directly by the user or by Visual Basic when the user quits the program.

Syntax

Sub AfterCloseFile(filename() As String)

The filename placeholder represents a string expression specifying the names of the files that have been closed.

Remarks

This event is triggered several times for each project in all the add-ins that are connected to the FileControl object; once for each .FRX file; once for all the forms, modules, classes, and each .VBX file; and once for the project file.  The add-in can't stop the project from being closed because the operation is complete; however, the add-in can log information about the event.


See Also

AfterWriteFile Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

DoGetOpenProjectName Event (Add-In)

RequestWriteFile Event (Add-In)


AfterCloseFile Event (Add-In) Applies To

FileControl Object (Add-In)


AfterRemoveFile Event (Add-In)

See Also	Applies To

Occurs after a file is removed from the active Visual Basic project.

Syntax

Sub AfterRemoveFile(filename As String)

The filename placeholder represents a string expression specifying the name of the file that has been removed.

Remarks

If an .FRX file is associated with a form, this event is triggered twice.  If a form is saved that previously required an .FRX file but no longer requires one, this event is triggered for the .FRX file.  This event is triggered in all the add-ins that are connected to the FileControl object.  The add-in can't stop the file from being removed because the operation is complete; however, the add-in can log information about the event, check out the project file, or prompt the user to delete the removed file.


See Also

AfterCloseFile Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

RequestWriteFile Event (Add-In)


AfterRemoveFile Event (Add-In) Applies To

FileControl Object (Add-In)


AfterWriteFile Event (Add-In)

See Also	Applies To

Occurs after a file is written to disk.

Syntax

Sub AfterWriteFile(filename As String, success As Integer)

The AfterWriteFile event syntax has these parts:

Part	Description

filename 	A string expression with the name of the file that has been written to disk.

success 	A value or constant specifying whether the file was actually written to disk, as described in Settings.

Settings

The settings for success are:

Constant	Value	Description

vbextWriteSuccess	0	Yes.

vbextWriteCancelled	1	Write was canceled.

vbextWriteFailed	2	Write failed.

Remarks

This event is triggered in all the add-ins that are connected to the FileControl object.  The add-in can't stop the file from being written to disk because the operation is complete; however, you can use this event to perform any of several useful tasks, such as:

Logging information about the event.

Updating information about the file.

Backing up the file.

Comparing versions of the executable (.EXE) file.


See Also

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

RequestWriteFile Event (Add-In)


AfterWriteFile Event (Add-In) Applies To

FileControl Object (Add-In)


Application Object (Add-In)

See Also	Properties	Methods	Events

Represents the application the add-in is connected to.

Syntax

Application

Remarks

This object exposes certain properties of the current instance of Visual Basic itself.  Using the properties of this object, all the objects that Visual Basic exposes to support add-ins can be accessed.  The Application object is passed to the ConnectAddIn event of an add-in object when the add-in is installed in an instance of Visual Basic.

The default value for the Application object is determined by the Name property.


See Also

Connecting an Add-in to Visual Basic

Creating Add-Ins

ProjectTemplate Object (Add-In)

Working with add-in objects


Application Object Properties
Application Object (Add-In) Properties

ActiveProject Property (Add-In)

AddInMenu Property (Add-In)

Application Property (Add-In)

FileControl Property (Add-In)

FullName Property (Add-In)

LastUsedPath Property (Add-In)

Name Property

Parent Property

ReadOnlyMode Property (Add-In)

Version Property (Add-In)


 Application Object Methods

LoadProject Method


 Application Object Events

ConnectAddIn Event (Add-In)

DisConnectAddIn Event (Add-In)


Application Property (Add-In)

See Also	Applies To

Returns the Application object representing the current instance of the Visual Basic development environment (VB.EXE).

Syntax

object.Application

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


See Also

Application Object (Add-In)

Parent Property


Application Property (Add-In) Applies To

Application Object (Add-In)

Component Object (Add-In)

ControlTemplate Object, ControlTemplates Collection (Add-In)

FileControl Object (Add-In)

FormTemplate Object (Add-In)

MenuItems Collection (Add-In)

MenuLine Object (Add-In)

ProjectTemplate Object (Add-In)

Property Object, Properties Collection (Add-In)

SelectedComponents Collection (Add-In)

SelectedControlTemplates Collection (Add-In)

SubMenu Object (Add-In)


BeforeLoadFile Event (Add-In)

See Also	Applies To

Occurs before a file or component is loaded into the active Visual Basic project.

Syntax

Sub BeforeLoadFile(filenames() As String)

The filenames placeholder represents a string expression containing the names of the files to be loaded, including any .VBX files referenced in a project (.VBP) file.

Remarks

This event is triggered in all the add-ins that are connected to the FileControl object.  This event is triggered several times for a project: once for the project file; once for all the forms, modules, classes, and .VBX files; and once for each of the .FRX files.  This event is fired when a project element is renamed because Visual Basic loads the newly renamed file.  The add-in can't stop the files from being loaded; however, the add-in can log information about the event, prepare the files to be loaded, or check out the files.


See Also

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

DoGetAddFileName Event (Add-In)


BeforeLoadFile Event (Add-In) Applies To

FileControl Object (Add-In)


ClassName Property (Add-In)

Applies To

Returns the class name of a control.

Syntax

object.ClassName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

This property setting is the same as the class name that is displayed for the control in the Visual Basic Properties window.

The ClassName property determines the default value for the ControlTemplate object.


ClassName Property (Add-In) Applies To

ControlTemplate Object (Add-In)


Component Object, Components Collection (Add-In)

Properties	Methods

Represents a component in a Visual Basic project.

Syntax

Component

Remarks

A component can be an .RES file, a form, a module, or a class.  This object allows the add-in to ascertain if the component's IsDirty property is set to True and the name(s) of the file(s) associated with this component.  This object also allows the add-in to save the component with a different filename.


Component Object Properties
Component Object, Components Collection (Add-In) Properties

Legend

Application Property (Add-In)

Count Property

FileCount Property (Add-In)

FileNames Property (Add-In)

IconState Property (Add-In)

IsDirty Property (Add-In)

Name Property

Parent Property


Component Object Methods
Component Object, Components Collection (Add-In) Methods

Legend

InsertFile Method (Add-In)

Item Method (Add-In)

Reload Method

SaveAs Method (Add-In)


ConnectAddIn Event (Add-In)

See Also	Applies To

Occurs when the add-in is added to an instance of Visual Basic.

Syntax

Sub ConnectAddIn(vbinstance As Object)

The vbinstance placeholder represents a pointer to an instance of the Application object.

Remarks

This event is triggered when a Visual Basic user clicks OK after selecting an add-in in the Add-In Manager dialog box or when an add-in listed in VB.INI with a value of 1 is loaded.  You can use vbinstance to access various objects in the instance of Visual Basic the add-in is connected to, such as the AddInMenu and LastUsedPath.  The add-in object initializes data structures, adds menus to the Visual Basic Add-Ins menu, and so on.  Because more than one instance of Visual Basic can install the add-in, you should never assume that only one instance of the class will be created.

Caution    Don't assign vbinstance to a global variable in the add-in; if the add-in is added to more than one instance of Visual Basic at the same time, the global variable holds only the most recent instance of vbinstance.


See Also

Application Object (Add-In)

DisconnectAddIn Event (Add-In)


ConnectAddIn Event (Add-In) Applies To

Application Object (Add-In)


ConnectEvents Method (Add-In)

See Also	Applies To

Connects an object from an add-in to Visual Basic so that the object can receive file control events (used with the FileControl object) or the selection of a menu item (used with the MenuItems collection).  Doesn't support named arguments.

Syntax

object.ConnectEvents (eventsink)

The ConnectEvents method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

eventsink	Required.  An object expression that evaluates to an object defined by a Visual Basic class module, specifying the object to be connected and to receive events from Visual Basic.

Return Value

The ConnectEvents method returns a long numeric value that contains the unique identifier you should pass to the DisconnectEvents method when disconnecting the add-in.

Remarks

For a FileControl object, eventsink should contain methods for the Visual Basic file control events that you want the add-in to receive; this object is called by Visual Basic when the events occur.

For a MenuLine object, eventsink should contain a method called AfterClick. When this menu item is clicked, Visual Basic triggers the AfterClick event, which in turn executes the AfterClick method contained in the eventsink.  Only one object can be connected to a particular MenuLine object.


See Also

DisconnectEvents Method (Add-In)


ConnectEvents Method (Add-In) Applies To

FileControl Object (Add-In)

MenuLine Object (Add-In)

ProjectTemplate Object (Add-In)


Container Property (Add-In)

See Also	Applies To

Returns or sets the FormTemplate object or ControlTemplate object representing the container for a control.

Syntax

object.Container [= container]

The Container property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

container	An object expression that specifies the new container for this control.

Remarks

The container may be a Form object or another control, such as a Frame control.  Because this property is read/write, new or existing controls can be put in a Frame control.


See Also

ControlTemplate Object, ControlTemplates Collection (Add-In)

FormTemplate Object (Add-In)


Container Property (Add-In) Applies To

ControlTemplate Object, ControlTemplates Collection (Add-In)


ControlTemplate Object, ControlTemplates Collection (Add-In)

See Also	Properties	Methods

Represents a control on a form or all the controls on a form.

Syntax

ControlTemplate

ControlTemplates

Remarks

A program can access an individual control or controls through the ControlTemplate object or ControlTemplates collection.  Using the ControlTemplate object, you can:

Access all the design time properties of a control.

Identify the container of the control.

Change the Z-order of the control.

Using the ControlTemplates collection, you can:

Access all the controls on a form.

Step through the collection of controls.

Return a specific control.

Add controls to a form.

The ClassName property determines the default value of the ControlTemplate object.  The Item method determines the default value of the ControlTemplates collection.


See Also

SelectedControlTemplates Collection (Add-In)


ControlTemplate Object, ControlTemplates Collection Properties
ControlTemplate Object, ControlTemplates Collection (Add-In) Properties

Legend

Application Property (Add-In)

ClassName Property (Add-In)

Container Property (Add-In)

Count Property

NewEnum Property (Add-In)

Parent Property

Properties Property (Add-In)


ControlTemplate Object, ControlTemplates Collection Methods
ControlTemplate Object, ControlTemplates Collection (Add-In) Methods

Legend

Add Method (Add-In)

Item Method (Add-In)

ZOrder Method


ControlTemplates Property (Add-In)

See Also	Applies To

Returns the ControlTemplates collection representing all the controls on a form.  Not available at design time.

Syntax

object.ControlTemplates

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

This property allows the program to access all the controls on a form.  The collection is empty if there are no controls on the active form.


See Also

ControlTemplate Object, ControlTemplates Collection (Add-In)


ControlTemplates Property (Add-In) Applies To

FormTemplate Object (Add-In)


DisconnectAddIn Event (Add-In)

See Also	Applies To

Occurs when an add-in is removed from an instance of Visual Basic.

Syntax

Sub DisconnectAddIn(mode As Integer)

The mode placeholder represents an integer that specifies the reason for the disconnection, as described in Settings.

Settings

The settings for mode are:

Setting	Description

0	The add-in is disconnected because the instance of Visual Basic is closed.

1	The add-in is disconnected because the user cleared the check box for the add-in in the AddIn Manager dialog box and chose OK.

Remarks

Triggering this event signifies that the add-in is about to be disconnected from this instance of Visual Basic and that specific actions should be completed, such as removing menus from the Visual Basic menu bar.  Because more than one instance of Visual Basic can be running, the add-in can be disconnected from a particular instance of Visual Basic but still be connected to other instances.


See Also

ConnectAddIn Event (Add-In)


DisconnectAddIn Event (Add-In) Applies To

Application Object (Add-In)


DisconnectEvents Method (Add-In)

See Also	Applies To

Disconnects an object in an add-in from Visual Basic so that the object ceases to receive file control events (used with the FileControl object) or menu item selection (used with a MenuLine object).  Doesn't support named arguments.

Syntax

object.DisconnectEvents hConnection

The DisconnectEvents method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

hConnection	Required.  A long value containing the unique identifier returned by the ConnectEvents method when connecting the add-in.


See Also

ConnectEvents Method (Add-In)


DisconnectEvents Method (Add-In) Applies To

FileControl Object (Add-In)

MenuLine Object (Add-In)

ProjectTemplate Object (Add-In)


DoGetAddFileName Event (Add-In)

See Also	Applies To

Occurs when the user chooses the Add File command from the File menu.

Syntax

Sub DoGetAddFileName(filenames( ) As String, canceldefault As Boolean)

The DoGetAddFileName event syntax has these parts:

Part	Description

filenames	A string expression specifying the name(s) of the file(s) to add to the project.  Each file specification must be relative to the current LastUsedPath property or a fully qualified filename.

canceldefault 	A Boolean expression used as a flag to cancel the default Visual Basic action, as described in Settings.

Settings

The settings for canceldefault are:

Setting	Description

True	Cancels the default Visual Basic action.  This event isn't triggered for any subsequent add-ins connected to the FileControl object.  If filenames(0) is a zero-length string when canceldefault is set to True, the event is canceled; otherwise, the file in filenames(0) is added to the project.

False	Continue triggering this event for subsequent add-ins connected to the FileControl object.  If no add-in sets canceldefault to True, the default Visual Basic Add File dialog box is displayed with the string you entered in filenames(0) selected.

Remarks

In Visual Basic version 4.0, only filenames(0) is significant: filenames(0) is a zero-length string ("") by default; any add-in that receives this event can change filenames(0).  The add-in can present a custom user interface and prompt the user for the name of the file to be added to the current project.  It can also change filenames(0) to reflect the user's choice.


See Also

AfterAddFile Event (Add-In)

BeforeLoadFile Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

LastUsedPath Property (Add-In)


DoGetAddFileName Event (Add-In) Applies To

FileControl Object (Add-In)


DoGetNewFileName Event (Add-In)

See Also	Applies To

Occurs when a user chooses the Save File or Save Project command from the File menu for a new file, chooses the Save File As or Save Project As command from the File menu for an existing file, or the Make EXE File command from the File menu.

Syntax

Sub DoGetNewFileName(filetype As Integer, newname As String, oldname As String, canceldefault As Boolean)

The DoGetNewFileName event syntax has these parts:

Part	Description

filetype 	A value or constant indicating the component type of the file, as described in Settings.

newname 	A string expression specifying the new name of the file.  The file specification must be relative to the current LastUsedPath property or a fully qualified filename.

oldname 	The old name of the file.

canceldefault	A Boolean expression that determines the default Visual Basic action, as described in Settings.

Settings

The settings for filetype are:

Constant	Value	Description

vbextFileTypeForm	0	Form

vbextFileTypeModule	1	Module

vbextFileTypeClass	2	Class

vbextFileTypeProject	3	Project

vbextFileTypeExe	4	.EXE

vbextFileTypeFrx	5	.FRX

vbextFileTypeRes	6	.RES

The settings for canceldefault are:

Setting	Description

True	Stops triggering this event for any subsequent add-ins connected to the FileControl object.  If newname is a zero-length string ("") when canceldefault is set to True, the event is canceled; otherwise, the name entered in newname is used as the new filename.

False	Continues triggering this event for subsequent add-ins connected to the FileControl object.  If no add-in sets canceldefault to True, the Save File As or Make EXE File dialog box is displayed with the string you entered in newname selected.

Remarks

The newname argument starts with the same value as oldname.  Any add-ins that receive this event can change newname.  The add-in can present a custom user interface to the user to get the new name of the file and can change newname to reflect the user's selection.


See Also

AfterChangeFileName Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

LastUsedPath Property (Add-In)


DoGetNewFileName Event (Add-In) Applies To

FileControl Object (Add-In)


DoGetOpenProjectName Event (Add-In)

See Also	Applies To

Occurs when the user chooses Open Project from the File menu or chooses another command that opens a project.  Exceptions are the New Project command on the File menu and Visual Basic opening the default project when it starts.

Syntax

Sub DoGetOpenProjectName(projectname As String, canceldefault As Boolean)

The DoGetOpenProjectName event syntax has these parts:

Part	Description

projectname	A string expression specifying the name of the project to be opened.  The file specification must be relative to the current LastUsedPath property or a fully qualified filename.

canceldefault	A Boolean expression that determines the default Visual Basic action, as described in Settings.

Settings

The settings for canceldefault are:

Setting	Description

True	Stops triggering this event for any subsequent add-ins connected to the FileControl object.  If projectname is a zero-length string, the event is canceled; otherwise, the project entered in projectname is opened.

False	Continues triggering this event for subsequent add-ins connected to the FileControl object.  If no add-in sets canceldefault to True, the Open Project dialog box is displayed with the string you entered in projectname selected.

Remarks

The projectname argument is initially a zero-length string; any add-ins that receive this event can change projectname.  The add-in can present a custom user interface that prompts the user for the project name and can change projectname to reflect the user's choice.


See Also

AfterCloseFile Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

LastUsedPath Property (Add-In)


DoGetOpenProjectName Event (Add-In) Applies To

FileControl Object (Add-In)


FileControl Object (Add-In)

See Also	Properties	Methods	Events

The object supplied by Visual Basic to support file control events.

Syntax

FileControl

Remarks

All notifications for file control are supervised by this object.  This object allows the add-in to specify which object within the add-in will receive file control events; this object is specified by the ConnectEvents and DisconnectEvents methods.  Once you specify the object within the add-in that will receive file control events, all file control events will cause a method to be invoked within the add-in object.

When more than one add-in connects an object to the FileControl object, the add-ins will be notified in the order in which they were connected.

A single action by a user can trigger several FileControl object events.  For example:

User action	Sequence of events
Changes a filename	DoGetNewFileName RequestChangeFileName RequestWriteFile (new filename) AfterWriteFile AfterChangeFileName
Adds a file to a project	DoGetAddFileName AfterAddFile
Chooses Make EXE command from the File menu	DoGetNewFileName RequestChangeFileName RequestWriteFile AfterWriteFile AfterChangeFileName
Note    Successfully invoking the AddFile method, the RemoveComponent method, or the SaveAs method causes the FileControl object to trigger events.


See Also

AddFile Method (Add-In)

FileControl Property

RemoveComponent Method (Add-In)

SaveAs Method (Add-In)


FileControl Object Properties
FileControl Object (Add-In) Properties

Application Property (Add-In)

Parent Property


FileControl Object Methods

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)


FileControl Object Events
FileControl Object (Add-In) Events

AfterAddFile Event (Add-In)

AfterChangeFileName Event (Add-In)

AfterCloseFile Event (Add-In)

AfterNewProject Event (Add-In)

AfterRemoveFile Event (Add-In)

AfterWriteFile Event (Add-In)

BeforeLoadFile Event (Add-In)

DoGetAddFileName Event (Add-In)

DoGetNewFileName Event (Add-In)

DoGetOpenProjectName Event (Add-In)

RequestChangeFileName Event (Add-In)

RequestWriteFile Event (Add-In)


FileControl Property (Add-In)

See Also	Applies To

Returns the FileControl object associated with the current instance of Visual Basic.

Syntax

object.FileControl

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The object returned by this property allows the add-in to register with Visual Basic to receive all file control events.


See Also

FileControl Object (Add-In)


FileControl Property (Add-In) Applies To

Application Object (Add-In)


FileCount Property (Add-In)

See Also	Applies To

Returns the number of files associated with a component.

Syntax

object.FileCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

For most components, this property setting is 1, but it can be greater.  For instance, if an .FRX file is associated with a form file, the FileCount property setting is 2.


See Also

FileNames Property (Add-In)


FileCount Property (Add-In) Applies To

Component Object, Components Collection (Add-In)


FileNames Property (Add-In)

See Also	Applies To

Returns the names of the files associated with a component.

Syntax

object.FileNames(index)

The FileNames property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An index specifying the filename in the indexed string to return.

Remarks

The number of entries in the indexed string is determined by the FileCount property setting.  The indexed string for classes and modules contains only one filename, while the indexed string for forms contains both the .FRM and .FRX filename for the form.  The values of the filenames are updated when the SaveAs method is invoked on the object.


See Also

FileCount Property (Add-In)

SaveAs Method (Add-In)


FileNames Property (Add-In) Applies To

Component Object (Add-In)


FormTemplate Object (Add-In)

See Also	Properties	Methods

Represents a form in a Visual Basic project.

Syntax

FormTemplate

Remarks

The properties, controls, and currently selected controls of a form are available through this object, and additional controls can be added.  This object also allows code to be added to the code module of the form and menus to be added to the form.

The currently active form is a FormTemplate object.


See Also

ActiveForm Property (Add-In)

ActiveProject Property (Add-In)


FormTemplate Object Properties
FormTemplate Object (Add-In) Properties

Application Property (Add-In)

ControlTemplates Property (Add-In)

Parent Property

Properties Property (Add-In)

SelectedControlTemplates Property (Add-In)


FormTemplate Object Methods
FormTemplate Object (Add-In) Methods

AddMenuTemplate Method (Add-In)

InsertFile Method (Add-In)


InsertFile Method (Add-In)

Applies To

Inserts code from a file into the code module of a form.  Doesn't support named arguments.

Syntax

object.InsertFile filename

The InsertFile method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filename	Required.  A string expression specifying the name of the file containing the code to be inserted into the code module.  A complete pathname can be used in filename; if the file isn't found, the directories searched by the Windows OpenFile function are searched, even if a complete pathname is specified.

Remarks

The code is inserted after the last declaration and before the first procedure in the code module.  The code is inserted as if the user had inserted the file using the Insert command on the File menu.


InsertFile Method (Add-In) Applies To

Component Object, Components Collection (Add-In)

FormTemplate Object (Add-In)


IsDirty Property (Add-In)

See Also	Applies To

Returns a value that indicates whether the component was edited since the last time it was saved.

Syntax

object.IsDirty

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The IsDirty property returns these values:

Value	Description

True	The component was edited since the last time it was saved.

False	The component wasn't edited since the last time it was saved.

Remarks

The SaveAs method sets the IsDirty property to False.


See Also

SaveAs Method (Add-In)


IsDirty Property (Add-In) Applies To

Component Object (Add-In)

ProjectTemplate Object (Add-In)


Item Method (Add-In)

See Also	Applies To

Returns an item from the specified collection.  Doesn't support named arguments.

Syntax

object.Item index

object.Item itemname

object.Item controlname, arrayindex

object.Item longindex

object.Item caption

The Item method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	Required.  For the Properties, Components, SelectedComponents, and SelectedControlTemplates collection, an integer specifying the index in the collection of the object to be accessed.

itemname	Required.  For the Properties, Components, SelectedComponents, and SelectedControlTemplates collection, a string expression specifying the name of the item to be accessed from the collection.  If the string doesn't match any member of the collection, an error occurs.

controlname	Required.  For the ControlTemplates collection, a string expression specifying the name of the ControlTemplate object to be accessed from the collection.  If the string doesn't match any member of the collection, an error occurs.

arrayindex	Optional.  For the ControlTemplates collection, an integer specifying the index in a control array of the ControlTemplate object to be accessed.

longindex	Required.  For the ControlTemplates collection, a long integer specifying the index in the collection of the object to be accessed.

caption	Required.  For the MenuItems collection, a string expression specifying the caption of the SubMenu object or MenuLine object to be accessed from the collection.  This argument must include an ampersand (&) before the character defined as the access key.  To specify an ampersand in a menu or menu item without defining an access key, use two ampersands (&&).  If the string doesn't match any member of the collection, an error occurs.

Remarks

There is no guarantee an index for a collection will point to the same item as items are added or deleted from the collection; using an index for the collection is useful only when iterating through the whole collection without adding or deleting items during the iteration.

The Item method determines the default value for these collections:

ControlTemplates

MenuItems

Properties

SelectedComponents

SelectedControlTemplates


See Also

Component Object, Components Collection (Add-In)

ControlTemplate Object, ControlTemplates Collection (Add-In)

Count Property (VB Collections)

MenuLine Object (Add-In)

Property Object, Properties Collection (Add-In)

SubMenu Object (Add-In)


Item Method (Add-In) Applies To

Component Object, Components Collection (Add-In)

ControlTemplate Object, ControlTemplates Collection (Add-In)

MenuItems Collection (Add-In)

Properties Collection (Add-In)

SelectedComponents Collection (Add-In)

SelectedControlTemplates Collection (Add-In)


LastUsedPath Property (Add-In)

See Also	Applies To

Returns or sets the last path used for the file dialog boxes used in Visual Basic, such as the Open Project dialog box.

Syntax

object.LastUsedPath [= pathname]

The LastUsedPath property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pathname	A string expression that specifies a filename that may include directory and drive specifications.


See Also

DoGetAddFileName Event (Add-In)

DoGetNewFileName Event (Add-In)

DoGetOpenProjectName Event (Add-In)


LastUsedPath Property (Add-In) Applies To

Application Object (Add-In)


SubMenu Object (Add-In)

See Also	Properties

Represents a menu in the Visual Basic development environment.

Syntax

SubMenu

Remarks

A SubMenu object contains a MenuItems collection, each menu item in the collection representing an individual item on the menu.

The default value for the SubMenu object is determined by the MenuItems property.


See Also

AddMenu Method (Add-In)

MenuLine Object (Add-In)

Remove Method (Add-In)


Menu Object Properties
SubMenu Object (Add-In) Properties

Application Property (Add-In)

Caption Property

Enabled Property

MenuItems Property (Add-In)

Parent Property


MenuItems Collection (Add-In)

Properties	Methods

Represents all entries in a particular menu, including all separator bars.

Syntax

MenuItems

Remarks

The items in this collection may be individual menu items, submenus, or both.  The default value for the MenuItems collection is determined by the Item method.


MenuItems Collection Properties
MenuItems Collection (Add-In) Properties

Application Property (Add-In)

Count Property

NewEnum Property (Add-In)

Parent Property


MenuItems Collection Methods
MenuItems Collection (Add-In) Methods

Add Method (Add-In)

AddMenu Method (Add-In)

Item Method (Add-In)

Remove Method (Add-In)


MenuItems Property (Add-In)

See Also	Applies To

Returns the MenuItems collection representing all the menu items in a menu.

Syntax

object.MenuItems

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The items in the collection may be menu items, submenus, or both.  The MenuItems property determines the default value for the SubMenu object.


See Also

MenuItems Collection (Add-In)


MenuItems Property (Add-In) Applies To

SubMenu Object (Add-In)


MenuLine Object (Add-In)

See Also	Properties	Methods	Events

Represents a menu item on a menu that isn't itself a submenu.

Syntax

MenuLine

Remarks

This menu item represents the final choice a user makes to carry out a command.  The default value for the MenuLine object is determined by the Caption property.


See Also

Add Method (Add-In)

Remove Method (Add-In)

SubMenu Object (Add-In)


MenuLine Object Properties
MenuLine Object (Add-In) Properties

Application Property (Add-In)

Caption Property

Checked Property

Enabled Property

HelpContextID Property

HelpFile Property

Parent Property


MenuLine Object Methods
MenuLine Object (Add-In) Methods

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)


MenuLine Object Events
MenuLine Object (Add-In) Events

AfterClick Event (Add-In)


NewEnum Property (Add-In)

See Also	Applies To

Returns an LPEnumVariant pointer representing the items in a collection.

Remarks

This property isn't directly visible to Visual Basic programmers; the For Each statement uses this property to allow the user to step through all the items in a collection.  C or C++ programmers can use this property to enumerate all the items in a collection.


See Also

Count Property

For Each...Next Statement

Item Method (Add-In)


NewEnum Property (Add-In) Applies To

ControlTemplate Object, ControlTemplates Collection (Add-In)

MenuItems Collection (Add-In)

Properties Collection (Add-In)

SelectedComponents Collection (Add-In)

SelectedControlTemplates Collection (Add-In)


ProjectTemplate Object (Add-In)

See Also	Properties	Methods	Events	Functions

Represents a project in Visual Basic.

Syntax

ProjectTemplate

Remarks

You can have only one project open at a time in Visual Basic version 4.0; this object represents the open project.  The valid ProjectTemplate object is determined by the ActiveProject property of the Application object.


See Also

ActiveProject Property (Add-In)

Application Object (Add-In)


ProjectTemplate Object Properties
ProjectTemplate Object (Add-In) Properties

ActiveForm Property (Add-In)

Application Property (Add-In)

FileName Property

IsDirty Property (Add-In)

Parent Property

SelectedComponents Property (Add-In)


ProjectTemplate Object Methods
ProjectTemplate Object (Add-In) Methods

AddFile Method (Add-In)

AddFormTemplate Method (Add-In)

AddMDIFormTemplate Method (Add-In)

AddReference Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxTypelib Method (Add-In)

AddToolboxVBX Method (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

RemoveComponent Method (Add-In)

WriteProperty Method (Add-In)


ProjectTemplate Object (Add-In) Functions

ReadProperty Function (Add-In)


ProjectTemplate Object (Add-In) Events

CheckIn Event (Add-In)

CheckOut Event (Add-In)

Fetch Event (Add-In)

UnCheckOut Event (Add-In)


Properties Property (Add-In)

See Also	Applies To

Returns the Properties collection representing the properties of a form or control.

Syntax

object.Properties

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The Properties collection contains all the properties of a form or control that can be accessed or modified at design time.  This property is not settable.


See Also

Property Object, Properties Collection (Add-In)


Properties Property (Add-In) Applies To

ControlTemplate Object, ControlTemplates Collection  (Add-In)

FormTemplate Object (Add-In)


Property Object, Properties Collection (Add-In)

Properties	Methods

A property or set of properties of a form or control.

Syntax

Property

Properties

Remarks

This object or collection includes all the properties that can normally be accessed at design time.  If the Property object is read/write, its Value property is read/write.  Accessing this property enables code to change the characteristics of a form or control.

The default value for the Property object is determined by the Value property.  The default value for the Properties collection is determined by the Item method.


Property Object, Properties Collection Properties
Property Object, Properties Collection (Add-In) Properties

Legend

Application Property (Add-In)

Count Property

IndexedValue Property (Add-In)

Name Property

NewEnum Property (Add-In)

NumIndices Property (Add-In)

Parent Property

Value Property


Property Object, Properties Collection Methods
Property Object, Properties Collection (Add-In) Methods

Legend

Item Method (Add-In)


Remove Method (Add-In)

See Also	Applies To

Removes a SubMenu or MenuLine object from a collection.  Doesn't support named arguments.

Syntax

object.Remove menuname

The Remove method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

menuname	Required.  An object expression that evaluates to a SubMenu object specifying the menu to be removed, or a MenuLine object specifying the menu item to be removed.


See Also

Add Method (Add-In)

AddMenu Method (Add-In)


Remove Method (Add-In) Applies To

MenuLine Object (Add-In)

SubMenu Object (Add-In)


RemoveComponent Method (Add-In)

See Also	Applies To

Removes a component from a project.  Doesn't support named arguments.

Syntax

object.RemoveComponent comp, save

The RemoveComponent method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

comp	Required.  An object expression that evaluates to a Component object specifying the component to be removed from the active project.

save	Required.  A Boolean expression specifying whether to save the component before removal, as described in Settings.

Settings

The settings for save are:

Setting	Description

True	Save the current memory image of the component.

False	Don't save the current memory image of the component.

Remarks

Successfully calling this method triggers the corresponding events from the FileControl object.


See Also

AddFile Method (Add-In)

AddFormTemplate Method (Add-In)

AddMDIFormTemplate Method (Add-In)

Component Object (Add-In)

FileControl Object (Add-In)

Reload Method (Add-In)


RemoveComponent Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


RequestChangeFileName Event (Add-In)

See Also	Applies To

Occurs after specifying a new filename for a component.

Syntax

Sub RequestChangeFileName(filetype As Integer, newname As String, oldname As String, cancelvalue As Boolean)

The RequestChangeFileName event syntax has these parts:

Part	Description

filetype 	A value or constant that indicates the component type of the file, as described in Settings.

newname	A string expression containing the name given to the renamed file.

oldname	A string expression containing the name of the file before it was renamed.

cancelvalue	A Boolean expression that determines the default Visual Basic action, as described in Settings.

Settings

The settings for filetype are:

Constant	Value	Description

vbextFileTypeForm	0	Form

vbextFileTypeModule	1	Module

vbextFileTypeClass	2	Class

vbextFileTypeProject	3	Project

vbextFileTypeExe	4	.EXE

vbextFileTypeFrx	5	.FRX

vbextFileTypeRes	6	.RES

The settings for cancelvalue are:

Setting	Description

True	Cancel the renaming of the file.  This event won't be triggered for any subsequent add-ins connected to the FileControl object.

False	Continue triggering this event for subsequent add-ins connected to the FileControl object.

Remarks

This event allows all the add-ins to inspect the new filename that is going to be added to the project and accept or cancel the name change.


See Also

AfterChangeFileName Event (Add-In)

ConnectEvents Method (Add-In)

DisconnectEvents Method (Add-In)

DoGetNewFileName Event (Add-In)


RequestChangeFileName Event (Add-In) Applies To

FileControl Object (Add-In)


RequestWriteFile Event (Add-In)

See Also	Applies To

Occurs prior to saving any project component with unsaved changes.

Syntax

Sub RequestWriteFile(filename As String, cancelvalue As Boolean)

The RequestWriteFile event syntax has these parts:

Part	Description

filename 	A string expression containing the name of the file to be saved.

cancelvalue 	A Boolean expression used as a flag to cancel the action, as described in Settings.

Settings

The settings for cancelvalue are:

Setting	Description

True	Doesn't write the file to disk.  This event isn't triggered for any subsequent add-ins connected to the FileControl object.

False	Continue triggering this event for subsequent add-ins connected to the FileControl object.

Remarks

If an .FRX file is associated with a form, this event is triggered twice.  This event allows add-ins to prepare the specified file for writing.  For example, this event enables an add-in to check out the file.


See Also

AfterRemoveFile Event (Add-In)

AfterWriteFile Event (Add-In)


RequestWriteFile Event (Add-In) Applies To

FileControl Object (Add-In)


SaveAs Method (Add-In)

See Also	Applies To

Saves a component using a new filename.  Doesn't support named arguments.

Syntax

object.SaveAs newfilename

The SaveAs method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

newfilename	Required.  A string expression specifying the new filename for the component to be saved.  If the new filename is invalid or refers to a read-only file, an error occurs.

Remarks

When a form is saved, newfilename specifies the new name of the form file itself; the .FRX file, if applicable, is saved automatically with the .FRX extension.

Note   Successfully invoking this method causes the associated events from the FileControl object to be invoked.


See Also

FileControl Object (Add-In)

IsDirty Property (Add-In)


SaveAs Method (Add-In) Applies To

Component Object, Components Collection  (Add-In)


SelectedComponents Property (Add-In)

See Also	Applies To

Returns the SelectedComponents collection representing the currently selected components in the project.

Syntax

object.SelectedComponents

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

In Visual Basic version 4.0, only one item is in the SelectedComponents collection.


See Also

SelectedComponents Collection (Add-In)


SelectedComponents Property (Add-In) Applies To

ProjectTemplate Object (Add-In)


SelectedComponents Collection (Add-In)

See Also	Properties	Methods

Contains all components (.RES file, form, module, class) that are currently selected in a project.

Syntax

SelectedComponents

Remarks

In Visual Basic version 4.0, there is only one component in the SelectedComponents collection.  The default value for the SelectedComponents collection is determined by the Item method.


See Also

SelectedComponents Property (Add-In)


SelectedComponents Collection Properties
SelectedComponents Collection (Add-In) Properties

Application Property (Add-In)

Count Property

NewEnum Property (Add-In)

Parent Property


SelectedComponents Collection Methods
SelectedComponents Collection (Add-In) Methods

Item Method (Add-In)


SelectedControlTemplates Collection (Add-In)

See Also	Properties	Methods

Contains all the selected controls on a form.

Syntax

SelectedControlTemplates

Remarks

Using this collection, all the controls that are currently selected can be accessed.  The code can step through the collection of controls or request a specific control.  This collection has the same specifications as the ControlTemplates collection, except this collection doesn't implement the Add method.

The default method for the SelectedControlTemplates collection is the Item method, and SelectedControlTemplates is indexed using integers.


See Also

ControlTemplate Object, ControlTemplates Collection (Add-In)


SelectedControls Collection Properties
SelectedControlTemplates Collection (Add-In) Properties

Application Property (Add-In)

Count Property

NewEnum Property (Add-In)

Parent Property


SelectedControls Collection Methods
SelectedControlTemplates Collection (Add-In) Methods

Item Method (Add-In)


SelectedControlTemplates Property (Add-In)

See Also	Applies To

Returns the SelectedControlTemplates collection representing the currently selected controls on a form.

Syntax

object.SelectedControlTemplates

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The collection is empty if no controls are currently selected on the form.


See Also

SelectedControlTemplates Collection (Add-In)


SelectedControlTemplates Property (Add-In) Applies To

FormTemplate Object (Add-In)


Value Property (Add-In)

See Also	Applies To

Returns or sets the value of a property.  Not available at design time.

Syntax

object.Value [= value]

The Value property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An expression that evaluates to a type compatible with the type of the property.

Remarks

If the Property object returned by the Value property is an element in a collection, the Value property returns a Properties collection.  If the property that the Property object represents is read/write at design time, then Value is read/write.  If the property is read-only, attempting to set the Value property causes an error.  If the property is write-only, attempting to return the Value property causes an error.

If the add-in interacts with the Value property and in doing so causes a critical error, an exception is generated.  If the add-in interacts with the Value property much as a user does and takes an action that typically causes a message box to be displayed, Visual Basic assumes the default for the message box.  For example, if the user renames a control to match the name of another control on the form, Visual Basic normally displays a message box prompting the user to create a control array.  If the add-in renames a control, Visual Basic assumes the default command, Yes, in the message box and creates a control array.

The Value property determines the default value for the Property object.

Note    If the add-in changes the name of a control in a control array, the control isn't automatically removed from the control array; the control array index must be set to -1 by the add-in after the control name is changed to remove the control from the control array.


See Also

Name Property

Property Object, Properties Collection (Add-In)


Value Property (Add-In) Applies To

Property Object (Add-In)


Version Property (Add-In)

See Also	Applies To

Returns the version number of the application the add-in is connected to.

Syntax

object.Version

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

This property value is a string beginning with one or two digits, a period, and two digits; the rest of the string is undefined and may contain text or numbers.


See Also

Name Property


Version Property (Add-In) Applies To

Application Object (Add-In)


FullName Property (Add-In)

Applies To

Returns the fully qualified path of the Visual Basic application.

Syntax

object.FullName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


FullName Method (Add-In) Applies To

Application Object (Add-In)


WriteProperty Method (Add-In)

See Also	Applies To

Writes a string to the specified section and key in the project's .VBP file.

Syntax

object.WriteProperty (section As String, key As String, value As String)

The WriteProperty method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

section	A string expression containing the name of the section where the key setting is located. If the specified section doesn't exist, it will be created.

key	A string expression containing the name of the key being written. If the specified key doesn't exist, it will be created.

value	A string expression containing the value the key is being set to.


See Also

ReadProperty Function (Add-In)

Properties Property (Add-In)

Property Object, Properties Collection (Add-In)


WriteProperty Method (Add-In) Applies To

ProjectTemplate Object (Add-In)


New Project Command (File Menu)

See Also

Creates a new project.

You can have only one project open at a time in Visual Basic, although you can run multiple instances of Visual Basic.  When you create a new project, Visual Basic prompts you to save your work in the current project, and 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 AUTO32LD.VBP or AUTO16LD.VBP project with the form modules, standard modules, class modules, custom controls, references, environment options, and format options you want for all new projects.

Available only at design time.


See Also

Add File Command (File Menu)

Custom Controls Dialog Box

Editor Options Tab

Environment Options Tab

Open Project Command (File Menu)

Project Command (View Menu)

Project Options Tab

References Dialog Box

Remove File Command (File Menu)

Save Project, Save Project As Commands (File Menu)


Open Project Command (File Menu)

See Also

Closes the current project, if a project is loaded, and loads an existing project.  Available only at design time.

Toolbar shortcut:  .  Keyboard shortcut: CTRL+O.

Note   If you are using an integrated source code control program, such as Microsoft SourceSafe (available with the Enterprise Edition), and have checked the project files out of the version control project, when you close a project (before opening a new one), a dialog may prompt you to check in the files you have checked out.

When you open a project in Visual Basic, a dialog may prompt you to get or check out the Visual Basic project files.

Dialog Box Options

File Name

Select or type the name of a project you want to open.

List Files of Type

Select a file type; the default is Project Files (*.VBP).  Files of the selected type will appear in the File Name list box.

Directories

Select the directory that contains the project you want to open.

Drives

Select a drive that contains the project you want to open.

OK

Opens the selected file.

Cancel

Closes the dialog box without opening a new project.

Network

Displays the Connect Network Drive dialog box so you can connect to a network drive to open a project on a remote drive.


See Also

Connecting to the SourceSafe Add-In

New Project Command (File Menu)

Options Command (Tools Menu)

Project Command (View Menu)

Save Project, Save Project As Commands (File Menu)


Save File, Save File As Commands (File Menu)

See Also

Saves the current form module, standard module, or class module to your disk with a name you specify.  The Save File command displays the Save File As dialog box if this is the first time the file is being saved.

The dialog box enables you to specify a new name for a form, MDI form, class module, or standard module.  Available only at design time.

Keyboard shortcuts: CTRL+S (Save File), CTRL+A (Save File As).

Note    If you are using an integrated source code control program, such as Microsoft SourceSafe (available with the Enterprise Edition), when you save a file with the Save File As command, a dialog may prompt you to add the file to the version control project. You can add a file to a SourceSafe project only if the Visual Basic project file (.VBP) is checked out.

When you use Save File As to rename a file that is checked out of a source code control program, the source code control program should also rename the file in the version control project.

Dialog Box Options

File Name

To save a file with a new name, or in a different location, type a new filename.  To save a file with an existing filename, select the name in the list or type the current name.  When you choose OK, Visual Basic asks if you want to overwrite the existing file. Unless you specify a filename extension, Visual Basic automatically adds the default filename extension .FRM for form modules, .CLS for class modules, and .BAS for standard modules.

List Files of Type

Select a file type from the list:

All Files (*.*) [image] Lists files of all types.

Form Files (*.FRM) [image] Lists all forms and MDI forms.

Class Files (*.CLS) [image] Lists all class modules.

Basic Files (*.BAS) [image] Lists all standard modules.

Directories

Select the directory where you want to store the file.

Drives

Select the drive where you want to store the file.

OK

Saves the file under the specified name.

Cancel

Closes the dialog box without saving the file.

Network

Displays the Connect Network Drive dialog box so you can connect to a network drive to save a file to a remote drive.


See Also

Add File Command (File Menu)

Connecting to the SourceSafe Add-In

Form, MDI Form, Module, and Class Module Commands (Insert Menu)

Save Project, Save Project As Commands (File Menu)

Saving Your Work


Save Project, Save Project As Commands (File Menu)

See Also

Saves the current project (.VBP) and all form modules, MDI forms, class modules, and standard modules in the current project.  Forms and projects are saved as ASCII text files.  Available only at design time.

Toolbar shortcut:

Dialog Box Options

File Name

To save a project with a new name, or in a different location, type a new filename.  To save a project with an existing filename, select the name in a list or type the current name.  When you choose OK, Visual Basic asks if you want to overwrite the existing file.  Unless you specify a filename extension, Visual Basic automatically adds the default filename extension .VBP.

List Files of Type

Select a file type from the list; the default is Project Files (*.VBP).  Files of the selected type will appear in the File Name list box.

Directories

Select the directory where you want to store the project file.

Drives

Select the drive where you want to store the project file.

OK

Saves the project under the specified name.

Cancel

Closes the dialog box without saving the project.

Network

Displays the Connect Network Drive dialog box so you can connect to a network drive to save a project to a remote drive.


See Also

Connecting to the SourceSafe Add-In

New Project Command (File Menu)

Open Project Command (File Menu)

Options Command (Tools Menu)

Project Command (View Menu)

Save File, Save File As Commands (File Menu)

Saving Your Work


Add File Command (File Menu)

See Also

Adds an existing form module, MDI form, class module, standard module, or resource file to your project.  You can share files between projects.  If you add a file to a project, you are simply including a reference to the existing file in the project; you are not adding a copy of the file to the project.  Therefore, if you make changes to the file and save it, your changes will affect any project that includes the file.  Available at design time only.

Keyboard shortcut: CTRL+D.

Note   Use the Custom Controls dialog box (Custom Controls command on the Tools menu) to add custom controls and insertable objects to your project's Toolbox.

Note    If you have connected to a source code control program, such as Microsoft SourceSafe (available with the Enterprise Edition), when you add a file to a Visual Basic project, a dialog may prompt you to add the file in the version control project.

With Microsoft SourceSafe, if the .VBP file is checked out, the references to the newly added file(s) are automatically added. If the .VBP file isn't checked out, when you add a file, the .VBP file will not contain a reference to the new file, and thus, it will not load the next time you open your project.

Dialog Box Options

File Name

Select or type the name of a file you want to open.  This box lists documents with the filename extension selected in the List Files of Type box.

List Files of Type

Select a file type from the list:

VB Files (*.FRM; *.BAS; *.CLS; *.RES) [image] Lists all valid Visual Basic file types.

Form Files (*.FRM) [image] Lists all form modules.

Basic Files (*.BAS) [image] Lists all standard modules.

Class Files (*.CLS) [image] Lists all class modules.

Resource Files (*.RES) [image] Lists all resource files.  There can be only one resource file in a single project.

All Files (*.*) [image] Lists all files.

Directories

Specify the directory that contains the file you want to add.

Drives

Select the drive that contains the file you want to add.

Network

Displays the Connect Network Drive dialog box so you can connect to a network drive to add a file from a remote drive.

OK

Adds the file to the project.

Cancel

Closes the dialog box without adding the file to the project.


See Also

Connecting to the SourceSafe Add-In

Custom Controls Dialog Box

Remove File Command (File Menu)


Remove File Command (File Menu)

See Also

From the Project Window, you can remove the currently selected form module, standard module, class module, or resource file from your project.  If you made changes to the file since last saving it, you are asked whether you want to save the changes first.  Available only at design time.

Note    If you are using an integrated source code control program, such as Microsoft SourceSafe (available with the Enterprise Edition), when you remove a file from your Visual Basic project, a dialog may prompt you to remove the file from the version control project.

With Microsoft SourceSafe, if the .VBP file is checked out, the references to the removed file(s) are automatically deleted. If the .VBP file isn't checked out, when you remove a file, the .VBP file will still contain a reference to the deleted file, causing an error the next time you load your project.

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 the standard procedures for your operating system.

When removing a form module, standard module, class module, or resource file from a project, make sure the remaining code doesn't refer to the removed file.

Note   Use the Custom Controls dialog box to remove a custom control from the Toolbox.  If you still have a custom control on a form, you can't remove the custom control from the Toolbox.


See Also

Add File Command (File Menu)

Connecting to the SourceSafe Add-In

Custom Controls Dialog Box


Print Setup Command (File Menu)

Displays the standard Print Setup dialog box with options to specify the printer, page orientation, paper size, and paper source, as well as other printing options.  Available only at design time.


Print Command (File Menu)

See Also

Prints forms and code to the printer specified in the Microsoft Windows Control Panel.  Available only at design time.

Keyboard shortcut: CTRL+P.

Dialog Box Options

Range

Determines the range you print:

Selection [image] Prints the currently selected code.

Current Module [image] Prints the forms and/or code for the currently selected module.

Project [image] Prints the forms and/or code for the entire project.

Print What

Determines what you print. You can select as many options as you like, depending on what you selected as the Range.

Form Image [image] Prints the form images.

Forms As Text [image] Prints the text representation of forms.  Use this feature to print all form and control properties and their values.

Code [image] Prints the code for the selected range.

Print Quality

Determines whether you print high, medium, low, or draft output quality.

Print to File

If selected, the output from this print function is sent to the file specified in the Print To File dialog box.  (This dialog box appears after you choose OK in the Print dialog box.)

OK

Prints your selection.

Cancel

Closes the dialog box without printing.

Setup

Displays the standard Print Setup dialog box.


See Also

Print Setup Command


Make EXE File Command (File Menu)

See Also

Creates an executable application by combining the form modules, standard modules, class modules, and resource files in a project into a single executable file (.EXE).

An executable file runs without opening or starting Visual Basic.  To run an executable file, the run-time file VB40016.DLL (for 16-bit operating systems) or VB40032.DLL (for 32-bit operating systems) must be in \WINDOWS\SYSTEM or a directory on the user's path.  You may also need other .DLL files, depending on the .EXE file's requirements.  See the SWDEPEND.INI file (located in the \WINDOWS directory) for a list of all file requirements.

This command doesn't affect the project's files.  You can still work with or modify your original files without affecting the executable file.

Dialog Box Options

File Name

Type the filename for the executable file, accept the default filename, or browse through the directories and select an existing filename to overwrite.  Unless you specify a filename extension, Visual Basic automatically uses the default filename extension .EXE.

Directories

Select the directory where you want to store the executable file.  You can browse through the directories to select an existing filename to overwrite.

Drives

Select the drive where you want to store the executable file.

OK

Makes an executable version of your application.

Cancel

Closes the dialog box without making an executable file.

Options

Displays the EXE Options dialog box, in which you can set the title and icon for your application, major and minor versioning information, and copyright, trademark, company name, and product name information.

Network

Displays the Connect Network Drive dialog box so that you can connect to a network drive and save your executable file on a remote drive.


See Also

EXE Options Dialog Box

Icon Property


Exit Command (File Menu)

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.

Note  When you exit Visual Basic, you may be prompted to check in the Visual Basic files to the source code control project if you are using an integrated source code control program, such as Microsoft SourceSafe (available with the Enterprise Edition), and you have any files checked out.


Redo, Undo Commands (Edit Menu)

See Also

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 can't be restored.  TabIndex is reset to the end of the tab order when you use Undo.  For forms, Undo is unavailable if the form has been edited since the last control deletion.

Keyboard shortcut: CTRL+Z.

Note    You can't undo a Cut operation using the Undo command.

Redo [image] Restores the last text editing Undo actions if no other actions have occurred since the last Undo.

Keyboard shortcut: CTRL+BACKSPACE.

For text edits, you can use Undo and Redo to restore up to twenty edits.

These commands are unavailable if there was no previous edit or if any other action has been performed after the last edit.  Also, some large edits may cause low memory conditions that could prevent an Undo action.  Visual Basic attempts to notify you when these conditions occur.


See Also

TabIndex Property


Cut, Copy, Paste, and Delete Commands (Edit Menu)

See Also

Cut [image] Removes the selected control or text and places it on the Clipboard.  You must select at least one character or control for this command to be available.

Keyboard shortcut: CTRL+X or SHIFT+DEL.

Copy [image] Copies the selected control or text onto the Clipboard.  You must select at least one character or control  for this command to be available.

Keyboard shortcut: CTRL+C or CTRL+INS.

Paste [image] Inserts the contents of the Clipboard at the current location.  Text is placed at the insertion point.  Pasted controls are placed at the upper-left corner of the active form.

When you paste a control, it has the same property settings (including the Name property setting) as the control you copied.  You can keep the same name and create a control array, or paste the control with a different name.  To paste a control inside another control, for instance a Frame, select the Frame and then paste the control into the Frame.

Keyboard shortcut: CTRL+V or SHIFT+INS.

Delete [image] Deletes the currently selected control, text, or watch expression.

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, use the standard deletion procedures for your operating system.

Keyboard shortcut: DEL.


See Also

Name Property

Remove File Command (File Menu)


Paste Link Command (Edit Menu)

Supports pasting a link to a valid DDE source.  Active only when the Clipboard contains a valid DDE source, and the selected control is a valid DDE sink.

You can also use Paste Link to link data from another application using the OLE container control.  Once you copy valid data onto the Clipboard (a paragraph from a word processor or a range of cells from a spreadsheet), you can select the OLE container control on your form, and then choose Paste Link to link the data.  Available only at design time.


Find Command (Edit Menu)

See Also

Searches for specified text in a specific search range.

Keyboard shortcuts: CTRL+F (Find), F3 (Find Next), or SHIFT+F3 (Find Previous).

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

Find What

Type or insert the information you want to find, or click the down arrow and select from the last four entries.  If any text is selected when you choose the command, this text is displayed in the Find What box.

Search

Specifies the search range.  Select:

Current Procedure [image] To search only the current procedure.

Current Module [image] To search only the current module.

Current Project [image] To search all the modules in your project.

Selected Text [image] To search a selected range of code in your project.

Direction

Sets the direction of the search to Down, Up, or All in the selected search range.

Find Whole Word Only

Searches for the full word by itself and not as part of a larger word.

Match Case

Finds all occurrences with the exact combination of uppercase and lowercase letters specified in the Find What box.

Use Pattern Matching

Searches using pattern-matching characters.

Find Next

Finds and selects the next occurrence of the text specified in the Find What box.

Cancel

Closes the dialog box without performing the search.

Replace

Displays the Replace dialog box, retaining the information typed in the Find What dialog box.


See Also

Finding a Procedure

Replace Command (Edit Menu)


Replace Command (Edit Menu)

See Also

Searches code in the project for the specified text and replaces it with new text.

Keyboard shortcut: CTRL+H

Dialog Box Options

Find What

Type or insert the information you want to find, or click the down arrow and select from the last four entries.  If any text is selected when you choose the command, this text is displayed in the Find What box.

Replace With

Type the text you want to use as the replacement text or paste it from the Clipboard.  To delete the text in the Find What box from the document, leave the Replace With box empty.

Search

Specifies the search range.  Select:

Current Procedure [image] To search only the current procedure.

Current Module [image] To search only the current module.

Current Project [image] To search all the modules in your project.

Selected Text [image] To search a selected range of code in your project.

Direction

Sets the direction of the search to Down, Up, or All in the selected search range.

Find Whole Word Only

Searches for the full word by itself and not as part of a larger word.

Match Case

Finds all occurrences with the exact combination of uppercase and lowercase letters specified in the Find What box.

Use Pattern Matching

Searches using pattern-matching characters.

Find Next

Finds and selects the next occurrence of the text specified in the Find What box.

Cancel

Closes the dialog box without replacing text.

Replace

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.


See Also

Find Command (Edit Menu)

Replacing Text in Code


Indent Command (Edit Menu)

See Also

Shifts all lines in the selection to the next tab stop.  The leftmost line in the selection is moved to the next tab stop, and then all other lines in the selection are moved the same number of spaces to retain the same relative indentation within the selected block.

Keyboard shortcut: TAB.


See Also

Outdent Command (Edit Menu)


Outdent Command (Edit Menu)

See Also

Shifts all lines in the selection to the previous tab stop.  The leftmost line in the selection is moved to the previous tab stop, and then all other lines in the selection are moved the same number of spaces to retain the same relative indentation within the selected block.

Keyboard shortcut: SHIFT+TAB.


See Also

Indent Command (Edit Menu)


Bring To Front, Send To Back Commands (Edit Menu)

See Also

Bring To Front [image] Moves the selected control to the front of all other objects.

Keyboard shortcut: CTRL+J.

Send To Back [image] Moves the selected control behind all other objects.

Keyboard shortcut: CTRL+K.

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

ZOrder Method


Align To Grid Command (Edit Menu)

See Also

Specifies whether the selected controls on a form automatically align to the grid.

To have all controls automatically align to the grid, select the Align Controls to Grid option in the Environment tab of the Options dialog box.


See Also

Environment Options Tab


Lock Command (Edit Menu)

Locks all controls on the form in their current positions so you don't inadvertently move them once they are in the desired location.  Because the Lock Controls command works on a form-by-form basis, it locks controls only on the selected form; controls on other forms are untouched.  Visual Basic keeps track of which forms have controls locked in position and which don't.  When the controls on the form are locked, the menu command has a check mark next to it.

Toolbar shortcut:  .


Code Command (View Menu)

See Also

Displays or activates the Code window for the current form module, standard module, or class module.

Keyboard shortcut: F7.


See Also

Code Window

Entering and Editing Code


Form Command (View Menu)

See Also

Displays the form for the currently selected form module.  Only available when the current module has an associated form.  Available only at design time.

Keyboard shortcut: SHIFT+F7.


See Also

Form Window


Procedure Definition Command (View Menu)

See Also

Displays the code for a procedure called from within another procedure.  For example, in the Form_Load procedure, you might call the mnuOpen_Click event procedure.  From within the Form_Load procedure, place the cursor anywhere in the procedure call to the mnuOpen_Click procedure, and then choose the Procedure Definition command.  The Code window jumps to the code associated with the mnuOpen_Click event procedure.

Keyboard shortcut: SHIFT+F2.


See Also

Entering and Editing Code

Last Position Command (View Menu)


Last Position Command (View Menu)

See Also

Allows you to quickly navigate to a previous location in your code.  Enabled only if you edited code or made a Procedure Definition command call and only when the Code window or Debug window is displayed.  For example, suppose you make a change to line 1, edit line 2, use the Procedure Definition command to jump to line 3, edit line 4, and then move to line 5.  When you choose Last Position, first line 4 is displayed; if you choose Last Position again, line 3 is displayed, and so on.  Visual Basic only keeps track of the last 4 lines that were accessed or edited.  Available at design time and in break mode.

Keyboard shortcut: CTRL+SHIFT+F2.


See Also

Procedure Definition


Object Browser Command (View Menu)

See Also

Displays the Object Browser, which lists the object libraries, classes, methods, and properties you can use in code, as well as the modules and procedures you defined for your project.  Not available at run time.

Toolbar shortcut: .  Keyboard shortcut: F2.

You can also click the Options button to add Help information or comments about the modules, procedures, classes, properties, and methods you create through the Object Browser. This lets you scroll through a list to see descriptions and comments for the procedures in your forms and modules.


See Also

Member Options Dialog Box

Object Browser


Debug Window Command (View Menu)

See Also

Opens or activates the Debug window.

Keyboard shortcut: CTRL+G.


See Also

Debug Object

Debug Window

Debugging Checklist


Project Command (View Menu)

See Also

Displays the Project Window, which displays a list of the project's form modules, class modules, standard modules and, if one exists, the resource file.

Toolbar shortcut:  .  Keyboard shortcut: CTRL+R.


See Also

Project Window


Properties Window Command (View Menu)

See Also

Displays the Properties Window, which lists the design-time properties for a selected form, control, class, module, or menu .  Available only at design time.

Toolbar shortcut:  .  Keyboard shortcut: F4.


See Also

Setting Colors

Setting Form and Control Properties

Properties Window


Toolbox Command (View Menu)

See Also

Displays the Toolbox, which contains all of the standard controls (.VBX), custom controls (.VBX and .OCX), and insertable objects (such as a Microsoft Excel Chart) available to your application.  Available only at design time.


See Also

Attaching an Event Procedure to a Form or Control

Custom Controls Command (Tools Menu)

Graphical Objects

Setting Form and Control Properties

Toolbox


Toolbar Command (View Menu)

See Also

Toggles the display of the toolbar, which contains buttons that are shortcuts to commonly used menu items and position and size indicators for a selected form or control.


See Also

Toolbar


Color Palette Command (View Menu)

See Also

Opens or activates the Color palette, which enables you to change a form or control's colors and set up a custom color scheme.  Available only at design time.


See Also

Color Palette

Setting Colors


Procedure Command (Insert Menu)

See Also

Inserts a new Sub, Function, or Property procedure.  The Insert Procedure dialog box also allows you to set the scope to public or private, and make all local variables in the procedure static.


See Also

Entering and Editing Code

Insert Procedure Dialog Box


Form, MDI Form, Module, and Class Module Commands (Insert Menu)

See Also

Choosing the Form command creates a new form and adds it to your project.

Form toolbar shortcut:

Choosing the MDI Form command creates a new multiple-document interface (MDI) form and adds it to your project.  Because a project can have only one MDI form, this command is unavailable if a project already has an MDI form.

Choosing the Module command inserts a new standard module and adds it to your project.

Module toolbar shortcut:

Choosing the Class Module command creates a new class module and adds it to your project.


See Also

MDIChild Property

New Project Command (File Menu)


File Command (Insert Menu)

Inserts existing text from other files into one of your modules.  Select the form module, class module, or standard module into which you want to insert text.  Move the cursor to the location where you want to begin the insertion.  When you choose the File command, you can enter the name of the file in the Insert File dialog box to insert its contents into the selected module.  Not available at run time.


Start Command (Run Menu)

See Also

Runs the application from the startup form (or Sub Main) specified in the Project tab of the Options dialog box.  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.  The Start command becomes the Break command at run time, and the Continue command in break mode.

Toolbar button:   Keyboard shortcut: F5.


See Also

Break Command (Run Menu)

Continue Command (Run Menu)

End Command (Run Menu)

Project Options Tab

Restart Command (Run Menu)


Continue Command (Run Menu)

See Also

Continues the execution of the application.

This command is available only in break mode.  The Continue command becomes the Start command at design time, and the Break command at run time.

Toolbar button:    Keyboard shortcut: F5.


See Also

Break Command (Run Menu)

End Command (Run Menu)

Project Options Tab

Restart Command (Run Menu)

Start Command (Run Menu)


Break Command (Run Menu)

See Also

Stops execution of a program while it's running and switches to break mode.  Any statement being executed when you choose this command is displayed in the Code pane of the Debug window with a thin-line border around it and highlighted with the colors you set in the Editor tab of the Options dialog box.  If the application is waiting for events in the idle loop (no statement is being executed), no statement is highlighted until an event occurs.

Some editing changes made in break mode may require you to restart your program for the changes to take effect.

This command is available at run time or in break mode.

Toolbar button:    Keyboard shortcut: F5 or CTRL+BREAK.


See Also

Continue Command (Run Menu)

Debug Window

Editor Options Tab

End Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)


End Command (Run Menu)

See Also

Stops running the program and returns to design time.  This command is available at run time and in break mode.

Toolbar shortcut:


See Also

Break Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)


Restart Command (Run Menu)

See Also

Restarts 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, a break expression changing or becoming true, or by pressing F5 while your application is running.

This command is available only in break mode.

Toolbar button:    Keyboard shortcut: SHIFT+F5.


See Also

Adding Watch Expressions

Break Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Setting and Clearing Breakpoints

Start Command (Run Menu)

Stop Statement


Step Into, Step Over, Step To Cursor Commands (Run Menu)

You can use Step Into to execute code one statement at a time.  Step Into executes the statement at the current execution point.  If the statement is a call to a procedure, the next statement displayed is the first statement in the procedure.  At design time, this menu item begins execution and enters break mode before the first line of code is executed.  Not available at run time.

Toolbar button:    Keyboard shortcut: F8.

Step Over is similar to Step Into.  The difference in use occurs when the current statement contains a call to a procedure.  Step Over executes it as a unit, and then steps to the next statement in the current procedure.  Therefore, the next statement displayed is the next statement in the current module regardless of whether the current statement is a call to a procedure.  Not available at run time.

Toolbar button:    Keyboard shortcut: SHIFT+F8.

When your application is in break mode, you can use Step To Cursor to select a statement further down in your code where you want execution to stop.  You could use this command, for example, to avoid executing large loops.  Not available at run time.

Keyboard shortcut: CTRL+F8.


Toggle Breakpoint Command (Run Menu)

See Also

Sets or removes a breakpoint at the current line.  You can't set a breakpoint on lines containing nonexecutable code such as comments, declaration statements, or blank lines.

A line of code in which a breakpoint has been set appears in the colors you specified in the Editor tab of the Options dialog box.

This command isn't available at run time.

Toolbar shortcut:    Keyboard shortcut: F9.


See Also

Add Watch Command (Tools Menu)

Adding Watch Expressions

Deleting Watch Expressions

Edit Watch Command (Tools Menu)

Editing Watch Expressions

Editor Options Tab

Instant Watch Command (Tools Menu)

Setting and Clearing Breakpoints


Clear All Breakpoints Command (Run Menu)

See Also

Removes all breakpoints in your project so your application can run in its entirety without breaking execution on a breakpoint.  Your application may still interrupt execution, however, if you have set a watch expression or selected the Break on All Errors option in the Advanced tab of the Options dialog box.  Not available at run time.

Keyboard shortcut: CTRL+SHIFT+F9.


See Also

Add Watch Command (Tools Menu)

Adding Watch Expressions

Advanced Options Tab

Deleting Watch Expressions

Edit Watch Command (Tools Menu)

Editing Watch Expressions

Instant Watch Command (Tools Menu)

Setting and Clearing Breakpoints

Toggle Breakpoint Command (Run Menu)


Set Next Statement Command (Run Menu)

See Also

You can set a different line of code to execute after the currently selected statement. The effect is similar to using Step Into, except Step Into executes only the next line of code in the procedure. Using Step Next Statement, you can choose a line of code located before or after the currently selected statement.  Any intervening code isn't executed.  Use this command to rerun a statement within the current procedure or to skip over statements you don't want to execute.  You can't use Step Next Statement for statements in different procedures.  This command is available only in break mode.

Keyboard shortcut: CTRL+F9.


See Also

Executing a Specific Statement

Step Into, Step Over, Step To Cursor Commands (Run Menu)


Show Next Statement Command (Run Menu)

See Also

You can use Show Next Statement to place the cursor on the line that will execute next.

This command is available only in break mode.


See Also

Executing a Specific Statement


Add Watch Command (Tools Menu)

See Also

At design time or in break mode, this command displays the Add Watch dialog box in which you enter a watch expression.  The expression can be any valid Basic expression.  If the Debug window is visible, watch expressions are updated in the Watch 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 (All Modules) or (All Procedures) could slow your program considerably, because Visual Basic evaluates the expression after executing each line of code.  Identifying a procedure for a context affects execution only while the selected procedure is in the list of active procedure calls, which you can see with the Calls command on the Tools menu.


See Also

Add Watch Dialog Box

Adding Watch Expressions

Calls Command (Tools Menu)

Deleting Watch Expressions

Editing Watch Expressions

Instant Watch Command (Tools Menu)

Setting and Clearing Breakpoints


Edit Watch Command (Tools Menu)

See Also

Displays the Edit Watch dialog box in which you can edit or delete a single watch expression, delete all watch expressions, or add watch expressions.

Keyboard shortcut: CTRL+W.


See Also

Add Watch Command (Tools Menu)

Adding Watch Expressions

Deleting Watch Expressions

Editing Watch Expressions

Edit Watch Dialog Box

Instant Watch Command (Tools Menu)

Setting and Clearing Breakpoints

Toggle Breakpoint Command (Run Menu)


Instant Watch Command (Tools Menu)

See Also

Displays the Instant Watch dialog box with the current value of the selected expression.  Available only in break mode.  While debugging your program, use this command to check the current value of a variable, property, or other expression for which you have not defined a watch expression.  Select the expression from either the Code window or the Code pane of the Debug window, and then choose the Instant Watch command.  If you want to add a watch expression based on the expression in the Instant Watch dialog box, choose the Add button.

Toolbar shortcut:    Keyboard shortcut: SHIFT+F9.


See Also

Add Watch Command (Tools Menu)

Adding Watch Expressions

Deleting Watch Expressions

Edit Watch Command (Tools Menu)

Editing Watch Expressions

Instant Watch Dialog Box

Setting and Clearing Breakpoints


Calls Command (Run Menu)

See Also

Displays the Calls dialog box, which lists the currently active procedure calls [image] procedures in the application that have started but are not completed.  Available only in 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 two procedures on the list of active procedure calls.  Each time a procedure calls another Sub, Function, or Property procedure, 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.

You can also display this dialog box by clicking the Calls button (...) next to the Procedure box in the Debug window.

Toolbar shortcut:    Keyboard shortcut: CTRL+L.


See Also

Calls Dialog Box


Menu Editor (Tools Menu)

See Also

Displays the Menu Editor dialog box.  Use the Menu Editor command to create custom menus for your application and to define some of their properties.

Toolbar shortcut:    Keyboard shortcut: CTRL+E.


See Also

Creating a Menu Bar

Menu Editor Dialog Box

Menu Editor Window Keys


Custom Controls Command (Tools Menu)

See Also

Displays the Custom Controls dialog box.  This dialog box allows you to add a VBX custom control, an OLE custom control (.OCX), or an insertable object (such as a Microsoft Word Document) to the Toolbox.


See Also

Custom Controls Dialog Box

Toolbox


References Command (Tools Menu)

See Also

Displays the References dialog box.  This dialog box allows you to add an object library or type library reference to your project. This makes another application's objects available in your code.  Once a reference is set, the application's objects are displayed in the Object Browser.


See Also

References Dialog Box

Object Browser


Options Command (Tools Menu)

See Also

Displays the Options dialog box, from which you can choose one of these four tabs to set attributes of the Visual Basic programming environment.

Environment

Project

Editor

Advanced


See Also

Advanced Options Tab

Environment Options Tab

Format Options Tab

Project Options Tab

Setting Options


Data Manager Command (Add-Ins Menu)

Opens or activates the Data Manager, if it is available.  Only available at design time.


Report Designer Command (Add-Ins Menu)

Opens or activates Crystal Reports for Visual Basic.  This menu item is only available in Visual Basic, Professional Edition, and only if you elected to install Crystal Reports during setup.  Only available at design time.


Add-In Manager Command (Add-Ins)

See Also

Displays the Add-In Manager, which you use to extend the Visual Basic development environment.


See Also

Add-In Manager


Help Menu Commands

Contents

Runs Help and displays the Visual Basic Table of Contents.

Search For Help On

Displays Help's Search dialog box 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.


Context Menus

Context menus are pop-up menus containing frequently used commands  Click the right mouse button to display these menus.

Context Menu for Controls at Design Time

Visual Basic context menus are available for controls at design time only.  For most controls, the menu items include the following.

Cut

Removes the selected controls from the form and copies them onto the Clipboard.

Copy

Copies the selected controls to the Clipboard.

Paste

Pastes the selected control(s) from the Clipboard into the selected control (if it is a Frame) or onto the upper-left corner of the form.

Clear

Deletes the selected controls and their contents from the form.

Align to Grid

Aligns the selected controls to the form's grid.

Properties

For standard controls, displays the standard Visual Basic Property window for the selected control.  For OLE custom controls, displays a customized Property window for the selected control.

View Code

Displays the Code window.

At run time, the control's context menu is provided by the control itself.  Custom controls may display other context menu items.

Context Menu for the Code Window at Design Time

The following menu items are displayed when you click the right mouse button in the editing region of a Code window at design time.

Cut

Cuts the selected text.  Only available if there is text selected.

Copy

Copies the selected text onto the Clipboard.  Only available if there is text selected.

Paste

Pastes the text from the Clipboard to the current insertion point.  Only available if there is text on the Clipboard.

Object Browser

Displays the Object Browser.

Procedure Definition

Displays the code for a procedure called from within another procedure.  For example, in the Form_Load procedure, you might call the mnuOpen_Click event procedure.  From within the Form_Load procedure, place the cursor anywhere in the procedure call to the mnuOpen_Click procedure, and then choose the Procedure Definition command.  The Code window jumps to the code associated with the mnuOpen_Click event procedure.

Toggle Breakpoint

Sets or removes a breakpoint.

Context Menu for the Code Window In Break Mode

The following menu items are displayed when you click the right mouse button in the Code pane of the Debug window while Visual Basic is in break mode.

Cut

Cuts the selected text.  Only available if text is selected.

Copy

Copies the selected text to the Clipboard.  Only available if there is text selected.

Paste

Pastes the text from the Clipboard to the current insertion point.  Only available if there is text on the Clipboard.

Object Browser

Displays the Object Browser.

Procedure Definition

Displays the code for a procedure called from within another procedure.  For example, in the Form_Load procedure, you might call the mnuOpen_Click event procedure.  From within the Form_Load procedure, place the cursor anywhere in the procedure call to the mnuOpen_Click procedure, and then choose the Procedure Definition command.  The Code window jumps to the code associated with the mnuOpen_Click event procedure.

Toggle Breakpoint

Sets or removes a breakpoint.

Step To Cursor

Steps over code and stops at a statement where you want execution to stop (the current insertion point).

Instant Watch

Displays the value of the expression.

Set Next Statement

Sets the current statement as the next statement to be executed.

Context Menu for the Immediate Pane In Break Mode

There is no context menu available in the Immediate pane of the Debug window at design time.  The Immediate pane itself can be viewed but can't be used to execute code at design time.  These menu items are available in break mode.

Cut

Cuts the selected text.  Only available if text is selected.

Copy

Copies the selected text onto the Clipboard.  Only available if there is text selected.

Paste

Pastes the text from the Clipboard to the current insertion point.  Only available if there is text on the Clipboard.

Object Browser

Displays the Object Browser.

Procedure Definition

Displays the code for a procedure called from within another procedure.  For example, in the Form_Load procedure, you might call the mnuOpen_Click event procedure.  From within the Form_Load procedure, place the cursor anywhere in the procedure call to the mnuOpen_Click procedure, and then choose the Procedure Definition command.  The Code window jumps to the code associated with the mnuOpen_Click event procedure.

Continue

Continues executing the application.  Same as pressing F5.

End

Ends the application.  Same as choosing End from the Run menu.

Context Menu for the Watch Pane in Break Mode and at Design Time

The following menu items are displayed when you click the right mouse button in the Watch pane of the Debug window during break mode or at design time.

Add Watch

Displays the Add Watch dialog box.

Edit Watch

Displays the Edit Watch dialog box for the selected watch expression.  Unavailable if there are no watch expressions.

Delete Watch

Deletes the selected watch expression.

Continue

Continues executing the application.  Only available in break mode.

End

Ends the application.  Only available in break mode.

Context Menu for the OLE Container Control

If an OLE container control has its own context menus (.OCX custom controls can define verbs that are displayed when you click the right mouse button), that context menu is merged with Visual Basic's context menu.  If the OLE container control contains an object, the object's verbs are displayed after the last separator bar.  For example, if the OLE container control contains a Microsoft Word document, the verbs displayed in the context menu might be Edit and Open.

In addition to the Cut, Copy, Paste, Clear, Align to Grid, and View Code menu commands, the context menu for the OLE container control has the following menu items.

Insert Object

Displays the Insert Object dialog box.  Always enabled.

Paste Special

Displays the Paste Special dialog box, which you can use to paste an object from the Clipboard into the OLE container control (available only when an object is on the Clipboard).

Create Link

Creates a link from the control to an object.  Only available when the SourceDoc property is set.

Create Embedded Object

Embeds an object in the control.  Only available when the Class or SourceDoc property is set.

Delete Embedded (or Linked) Object

Deletes an existing linked or embedded object in the control.  Only available if the OLE container control contains a linked or embedded object.

Context Menu for Forms

Context menus are available on the form at design time only.  The context menu for the form is displayed if you click the right mouse button only while the pointer isn't over a control on the form.

Paste

Pastes the contents of the Clipboard to the form.

Properties

Displays the Property window for the selected form.

Menu Editor

Displays the Menu Editor.

View Code

Displays the Code window for the selected form module.


Code Window Keyboard Shortcuts

You can use the following shortcut keys to access commands in the Code window.

Description	Shortcut Keys

View Code window	F7

Display Objects list box	CTRL+F2

View Object Browser	F2

Find	CTRL+F

Replace	CTRL+H

Find Next	F3

Find Previous	SHIFT+F3

Next procedure	CTRL+DOWN ARROW

Previous procedure	CTRL+UP ARROW

Go to procedure	SHIFT+F2

Shift one screen down	CTRL+PAGE DOWN

Shift one screen up	CTRL+PAGE UP

Go to last position	CTRL+SHIFT+F2

Beginning of module	CTRL+HOME

End of module	CTRL+END

Move one word to right	CTRL+RIGHT ARROW

Move one word to left	CTRL+LEFT ARROW

Move to end of line	END

Move to beginning of line	HOME

Insert new line	CTRL+N

Redo	CTRL+BACKSPACE

Undo	CTRL+Z

Delete current line	CTRL+Y

Delete to end of word	CTRL+DEL

Indent	TAB

Outdent	SHIFT+TAB

Clear all breakpoints	CTRL+SHIFT+F9


Check Out Command (Tools Menu)

See Also

Copies one or more selected files from the current project in the source code control program (such as Microsoft SourceSafe, which is available with the Enterprise Edition) into your current working directory so that you can modify them. When you check out a file, a check mark appears to the left of the filename in the Visual Basic Project window.

Note   One of the main differences between the Check Out and Get commands is that the Get command places a read-only local copy of a file in your working directory, whereas the Check Out command places a read/write local copy of the file in your working directory.

You must have permission to check out files in the source code control program to use this command.

To enable this and the Check In, Get, and Undo Check Out commands, you must first connect the source code control program add-in and add a project to it.


See Also

Check In Command (Tools Menu)

Connecting to the SourceSafe Add-In

Get Command (Tools Menu)

Undo Check Out Command (Tools Menu)


Check In Command (Tools Menu)

See Also

Updates the source code control program (such as Microsoft SourceSafe, which is available with the Enterprise Edition) with changes made to a checked out file, and unlocks the source code control program's master copy.  With SourceSafe, clicking Check In displays the Checkin dialog box.

You must have permission to check out files in the source code control program to use this command.

To enable this and the Get, Check Out, and Undo Check Out commands, you must first connect the source code control program add-in and add a project to it.


See Also

Check Out Command (Tools Menu)

Connecting to the SourceSafe Add-In

Get Command (Tools Menu)

Undo Check Out Command (Tools Menu)


Get Command (Tools Menu)

See Also

The Get command retrieves read-only copies of the most recent version of a file, a group of files, or an entire project from the source code control program (such as Microsoft SourceSafe, which is available with the Enterprise Edition) and creates read-only copies for viewing or compiling in your working directory.

Note   One of the main differences between the Check Out and Get commands is that the Get command places a read-only local copy of a file in your working directory, whereas the Check Out command places a read/write local copy of the file in your working directory.

You must have permission to read files to use this command.

To enable this and the Check In, Check Out, and Undo Check Out commands, you must first connect the source code control program add-in and add a project to it.


See Also

Check In Command (Tools Menu)

Check Out Command (Tools Menu)

Connecting to the SourceSafe Add-In

Undo Check Out Command (Tools Menu)


Undo Check Out Command (Tools Menu)

See Also

Cancels a Check Out operation, voiding all changes.

You must have permission to check out files in the source code control program, and you must have one or more files checked out to use this command.

To enable this and the Get, Check In, and Check Out commands, you must first connect the source code control program add-in and add a project to it.


See Also

Check In Command (Tools Menu)

Check Out Command (Tools Menu)

Connecting to the SourceSafe Add-In

Get Command (Tools Menu)


Miscellaneous Constants

See Also

ZOrder Method

Constant	Value	Description

vbBringToFront	0	Bring to front.

vbSendToBack	1	Send to back.

QueryUnload Method

Constant	Value	Description

vbAppWindows	2	Current Windows session ending.

vbFormMDIForm	4	MDI child form is closing because the MDI form is closing.

vbFormCode	1	Unload method invoked from code.

vbFormControlMenu	0	User has chosen Close command from the Control-menu box on a form.

vbAppTaskManager	3	Windows Task Manager is closing the application.

Shift Parameter Masks

Constant	Value	Description

vbShiftMask	1	SHIFT key bit mask.

vbCtrlMask	2	CTRL key bit mask.

vbAltMask	4	ALT key bit mask.

Button Parameter Masks

Constant	Value	Description

vbLeftButton	1	Left mouse button.

vbRightButton	2	Right mouse button.

vbMiddleButton	4	Middle mouse button.

Application Start Mode

Constant	Value	Description

vbSModeStandalone	0	Stand-alone application.

vbSModeAutomation	1	OLE automation server.

LoadResPicture Method

Constant	Value	Description

vbResBitmap	=0;	Bitmap resource.

vbResIcon	=1;	Icon resource.

vbResCursor	=2;	Cursor resource.

Check Value

Constant	Value	Description

vbUnchecked	=0;	Unchecked.

vbChecked	=1;	Checked.

vbGrayed	=2;	Grayed.


See Also

Alignment Constants

Border Property Constants

Clipboard Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Control Constants

See Also

ComboBox Control

Constant	Value	Description

vbComboDropdown	0	Dropdown Combo.

vbComboSimple	1	Simple Combo.

vbComboDropdownList	2	Dropdown List.

ListBox Control

Constant	Value	Description

vbMultiSelectNone	0	None.

vbMultiSelectSimple	1	Simple.

vbMultiSelectExtended	2	Extended.

ScrollBar Control

Constant	Value	Description

vbSBNone	0	None.

vbHorizontal	1	Horizontal.

vbVertical	2	Vertical.

vbBoth	3	Both.

Shape Control

Constant	Value	Description

vbShapeRectangle	0	Rectangle.

vbShapeSquare	1	Square.

vbShapeOval	2	Oval.

vbShapeCircle	3	Circle.

vbShapeRoundedRectangle	4	Rounded rectangle.

vbShapeRoundedSquare	5	Rounded square.


See Also

Alignment Constants

Border Property Constants

Clipboard Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Miscellaneous Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Grid Control Constants

See Also

ColAlignment, FixedAlignment Properties

Constant	Value	Description

grdAlignCenter	2	Center data in column.

grdAlignLeft	0	Left-align data in column.

grdAlignRight	1	Right-align data in column.

FillStyle Property

Constant	Value	Description

grdSingle	0	Changing Text property setting affects only active cell.

grdRepeat	1	Changing Text property setting affects all selected cells.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Picture Object Constants

See Also

Constant	Value	Description

vbPicTypeBitmap	1	Bitmap type of Picture object.

vbPicTypeMetafile	2	Metafile type of Picture object.

vbPicTypeIcon	3	Icon type of Picture object.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Variant Type Constants

See Also

Constant	Value	Description

vbVEmpty	0	Empty (uninitialized).

vbVNull	1	Null (no valid data).

vbVInteger	2	Integer data type.

vbVLong	3	Long integer data type.

vbVSingle	4	Single-precision floating-point data type.

vbVDouble	5	Double-precision floating-point data type.

vbVCurrency	6	Currency (scaled integer) data type.

vbVDate	7	Date data type.

vbVString	8	String data type.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

VBTranslateColor/OLETranslateColor Constants


DDE Constants

See Also

linkerr (LinkError Event)

Constant	Value	Description

vbWrongFormat	1	Another application requested data in wrong format.

vbDDESourceClosed	6	Destination application attempted to continue after source closed.

vbTooManyLinks	7	All source links are in use.

vbDataTransferFailed	8	Failure to update data in destination.

LinkMode Property (Forms and Controls)

Constant	Value	Description

vbLinkNone	0	None.

vbLinkSource	1	Source (forms only).

vbLinkAutomatic	1	Automatic (controls only).

vbLinkManual	2	Manual (controls only).

vbLinkNotify	3	Notify (controls only).

LinkMode Property (Only for backward compatibility with Visual Basic version 1.0; use new constants instead).

Constant	Value	Description

vbHot	1	Hot (controls only).

vbServer	1	Server (forms only).

vbCold	2	Cold (controls only).


See Also

Alignment Constants

Border Property Constants

Clipboard Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Clipboard Object Constants

See Also

Constant	Value	Description

vbCFLink	0xBF00	DDE conversation information.

vbCFRTF	0xBF01	Rich Text Format (.RTF file).

vbCFText	1	Text (.TXT file).

vbCFBitmap	2	Bitmap (.BMP file).

vbCFMetafile	3	Metafile (.WMF file).

vbCFDIB	8	Device-independent bitmap.

vbCFPalette	9	Color palette.


See Also

Alignment Constants

Border Property Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Drag-and-Drop Constants

See Also

DragOver Event

Constant	Value	Description

vbEnter	0	Source control dragged into target.

vbLeave	1	Source control dragged out of target.

vbOver	2	Source control dragged from one position in target to another.

Drag Method (Controls)

Constant	Value	Description

vbCancel	0	Cancel drag operation.

vbBeginDrag	1	Begin dragging control.

vbEndDrag	2	Drop control.

DragMode Property

Constant	Value	Description

vbManual	0	Manual.

vbAutomatic	1	Automatic.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Form Constants

See Also

Show Parameters

Constant	Value	Description

vbModal	1	Modal form.

vbModeless	0	Modeless form.

Arrange Method for MDI Forms

Constant	Value	Description

vbCascade	0	Cascade all nonminimized MDI child forms.

vbTileHorizontal	1	Horizontally tile all nonminimized MDI child forms.

vbTileVertical	2	Vertically tile all nonminimized MDI child forms.

vbArrangeIcons	3	Arrange icons for minimized MDI child forms.

WindowState Property

Constant	Value	Description

vbNormal	0	Normal.

vbMinimized	1	Minimized.

vbMaximized	2	Maximized.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Key Code Constants

See Also

Key Codes

Constant	Value	Description

vbKeyLButton	0x1	Left mouse button.

vbKeyRButton	0x2	Right mouse button.

vbKeyCancel	0x3	CANCEL key.

vbKeyMButton	0x4	Middle mouse button.

vbKeyBack	0x8	BACKSPACE key.

vbKeyTab	0x9	TAB key.

vbKeyClear	0xC	CLEAR key.

vbKeyReturn	0xD	ENTER key.

vbKeyShift	0x10	SHIFT key.

vbKeyControl	0x11	CTRL key.

vbKeyMenu	0x12	MENU key.

vbKeyPause	0x13	PAUSE key.

vbKeyCapital	0x14	CAPS LOCK key.

vbKeyEscape	0x1B	ESC key.

vbKeySpace	0x20	SPACEBAR key.

vbKeyPageUp	0x21	PAGE UP key.

vbKeyPageDown	0x22	PAGE DOWN key.

vbKeyEnd	0x23	END key.

vbKeyHome	0x24	HOME key.

vbKeyLeft	0x25	LEFT ARROW key.

vbKeyUp	0x26	UP ARROW key.

vbKeyRight	0x27	RIGHT ARROW key.

vbKeyDown	0x28	DOWN ARROW key.

vbKeySelect	0x29	SELECT key.

vbKeyPrint	0x2A	PRINT SCREEN key.

vbKeyExecute	0x2B	EXECUTE key.

vbKeySnapshot	0x2C	SNAPSHOT key.

vbKeyInsert	0x2D	INS key.

vbKeyDelete	0x2E	DEL key.

vbKeyHelp	0x2F	HELP key.

vbKeyNumlock	0x90	NUM LOCK key.

KeyA Through KeyZ Are the Same as Their ASCII Equivalents: 'A' Through 'Z'

Constant	Value	Description

vbKeyA	65	A key.

vbKeyB	66	B key.

vbKeyC	67	C key.

vbKeyD	68	D key.

vbKeyE	69	E key.

vbKeyF	70	F key.

vbKeyG	71	G key.

vbKeyH	72	H key.

vbKeyI	73	I key.

vbKeyJ	74	J key.

vbKeyK	75	K key.

vbKeyL	76	L key.

vbKeyM	77	M key.

vbKeyN	78	N key.

vbKeyO	79	O key.

vbKeyP	80	P key.

vbKeyQ	81	Q key.

vbKeyR	82	R key.

vbKeyS	83	S key.

vbKeyT	84	T key.

vbKeyU	85	U key.

vbKeyV	86	V key.

vbKeyW	87	W key.

vbKeyX	88	X key.

vbKeyY	89	Y key.

vbKeyZ	90	Z key.

Key0 Through Key9 Are the Same as Their ASCII Equivalents: '0' Through '9'

Constant	Value	Description

vbKey0	48	0 key.

vbKey1	49	1 key.

vbKey2	50	2 key.

vbKey3	51	3 key.

vbKey4	52	4 key.

vbKey5	53	5 key.

vbKey6	54	6 key.

vbKey7	55	7 key.

vbKey8	56	8 key.

vbKey9	57	9 key.

Keys on the Numeric Keypad

Constant	Value	Description

vbKeyNumpad0	0x60	0 key.

vbKeyNumpad1	0x61	1 key.

vbKeyNumpad2	0x62	2 key.

vbKeyNumpad3	0x63	3 key.

vbKeyNumpad4	0x64	4 key.

vbKeyNumpad5	0x65	5 key.

vbKeyNumpad6	0x66	6 key.

vbKeyNumpad7	0x67	7 key.

vbKeyNumpad8	0x68	8 key.

vbKeyNumpad9	0x69	9 key.

vbKeyMultiply	0x6A	MULTIPLICATION SIGN (*) key.

vbKeyAdd	0x6B	PLUS SIGN (+) key.

vbKeySeparator	0x6C	ENTER key.

vbKeySubtract	0x6D	MINUS SIGN (-) key.

vbKeyDecimal	0x6E	DECIMAL POINT(.) key.

vbKeyDivide	0x6F	DIVISION SIGN (/) key.

Function Keys

Constant	Value	Description

vbKeyF1	0x70	F1 key.

vbKeyF2	0x71	F2 key.

vbKeyF3	0x72	F3 key.

vbKeyF4	0x73	F4 key.

vbKeyF5	0x74	F5 key.

vbKeyF6	0x75	F6 key.

vbKeyF7	0x76	F7 key.

vbKeyF8	0x77	F8 key.

vbKeyF9	0x78	F9 key.

vbKeyF10	0x79	F10 key.

vbKeyF11	0x7A	F11 key.

vbKeyF12	0x7B	F12 key.

vbKeyF13	0x7C	F13 key.

vbKeyF14	0x7D	F14 key.

vbKeyF15	0x7E	F15 key.

vbKeyF16	0x7F	F16 key.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Color Constants

See Also

Colors

Constant	Value	Description

vbBlack	0x0	Black.

vbRed	0xFF	Red.

vbGreen	0xFF00	Green.

vbYellow	0xFFFF	Yellow.

vbBlue	0xFF0000	Blue.

vbMagenta	0xFF00FF	Magenta.

vbCyan	0xFFFF00	Cyan.

vbWhite	0xFFFFFF	White.

System Colors

Constant	Value	Description

vbScrollBars	0x80000000	Scroll bar color.

vbDesktop	0x80000001	Desktop color.

vbActiveTitleBar	0x80000002	Color of the title bar for the active window.

vbInactiveTitleBar	0x80000003	Color of the title bar for the inactive window.

vbMenuBar	0x80000004	Menu background color.

vbWindowBackground	0x80000005	Window background color.

vbWindowFrame	0x80000006	Window frame color.

vbMenuText	0x80000007	Color of text on menus.

vbWindowText	0x80000008	Color of text in windows.

vbTitleBarText	0x80000009	Color of text in caption, size box, and scroll arrow.

vbActiveBorder	0x8000000A	Border color of active window.

vbInactiveBorder	0x8000000B	Border color of inactive window.

vbApplicationWorkspace	0x8000000C	Background color of multiple-document interface (MDI) applications.

vbHighlight	0x8000000D	Background color of items selected in a control.

vbHighlightText	0x8000000E	Text color of items selected in a control.

vbButtonFace	0x8000000F	Color of shading on the face of command buttons.

vbButtonShadow	0x80000010	Color of shading on the edge of command buttons.

vbGrayText	0x80000011	Grayed (disabled) text.

vbButtonText	0x80000012	Text color on push buttons.

vbInactiveCaptionText	0x80000013	Color of text in an inactive caption.

vb3DHighlight	0x80000014	Highlight color for 3D display elements.

vb3DDKShadow	0x80000015	Darkest shadow color for 3D display elements.

vb3DLight	0x80000016	Second lightest of the 3D colors after vb3DHighlight.

vbInfoText	0x80000017	Color of text in ToolTips.

vbInfoBackground	0x80000018	Background color of ToolTips.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Alignment Constants

See Also

Align Property

Constant	Value	Description

vbAlignNone	0	Size and location set at design time or in code.

vbAlignTop	1	Picture box at top of form.

vbAlignBottom	2	Picture box at bottom of form.

vbAlignLeft	3	Picture box at left of form.

vbAlignRight	4	Picture box at right of form.

Alignment Property

Constant	Value	Description

vbLeftJustify	0	Left align.

vbRightJustify	1	Right align.

vbCenter	2	Center.


See Also

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Border Property Constants

See Also

BorderStyle Property (Form)

Constant	Value	Description

vbBSNone	0	No border.

vbFixedSingle	1	Fixed single.

vbSizable	2	Sizable (forms only).

vbFixedDouble	3	Fixed double (forms only).

BorderStyle Property (Shape and Line)

Constant	Value	Description

vbTransparent	0	Transparent.

vbBSSolid	1	Solid.

vbBSDash	2	Dash.

vbBSDot	3	Dot.

vbBSDashDot	4	Dash-dot.

vbBSDashDotDot	5	Dash-dot-dot.

vbBSInsideSolid	6	Inside solid.


See Also

Alignment Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Mouse Pointer Constants

See Also

Constant	Value	Description

vbDefault	0	Default.

vbArrow	1	Arrow.

vbCrosshair	2	Cross.

vbIbeam	3	I beam.

vbIconPointer	4	Icon.

vbSizePointer	5	Size.

vbSizeNESW	6	Size NE, SW.

vbSizeNS	7	Size N, S.

vbSizeNWSE	8	Size NW, SE.

vbSizeWE	9	Size W, E.

vbUpArrow	10	Up arrow.

vbHourglass	11	Hourglass.

vbNoDrop	12	No drop.

vbArrowHourglass	13	Arrow and hourglass. (Only available in 32-bit Visual Basic 4.0.)

vbArrowQuestion	14	Arrow and question mark. (Only available in 32-bit Visual Basic 4.0.)

vbSizeAll	15	Size all. (Only available in 32-bit Visual Basic 4.0.)

vbCustom	99	Custom icon specified by the MouseIcon property.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Drawing Constants

See Also

DrawMode Property

Constant	Value	Description

vbBlackness	1	Black.

vbNotMergePen	2	Not Merge pen.

vbMaskNotPen	3	Mask Not pen.

vbNotCopyPen	4	Not Copy pen.

vbMaskPenNot	5	Mask pen Not.

vbInvert	6	Invert.

vbXorPen	7	Xor pen.

vbNotMaskPen	8	Not Mask pen.

vbMaskPen	9	Mask pen.

vbNotXorPen	10	Not Xor pen.

vbNop	11	No operation; output remains unchanged.

vbMergeNotPen	12	Merge Not pen.

vbCopyPen	13	Copy pen.

vbMergePenNot	14	Merge pen Not.

vbMergePen	15	Merge pen.

vbWhiteness	16	White.

DrawStyle Property

Constant	Value	Description

vbSolid	0	Solid.

vbDash	1	Dash.

vbDot	2	Dot.

vbDashDot	3	Dash-dot.

vbDashDotDot	4	Dash-dot-dot.

vbInvisible	5	Invisible.

vbInsideSolid	6	Inside solid.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Graphics Constants

See Also

FillStyle Property

Constant	Value	Description

vbFSSolid	0	Solid.

vbFSTransparent	1	Transparent.

vbHorizontalLine	2	Horizontal line.

vbVerticalLine	3	Vertical line.

vbUpwardDiagonal	4	Upward diagonal.

vbDownwardDiagonal	5	Downward diagonal.

vbCross	6	Cross.

vbDiagonalCross	7	Diagonal cross.

ScaleMode Property

Constant	Value	Description

vbUser	0	User.

vbTwips	1	Twips.

vbPoints	2	Points.

vbPixels	3	Pixels.

vbCharacters	4	Characters.

vbInches	5	Inches.

vbMillimeters	6	Millimeters.

vbCentimeters	7	Centimeters.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


OLE Container Control Constants

See Also

OLEType Property

Constant	Value	Description

vbOLELinked	0	OLE container control contains a linked object.

vbOLEEmbedded	1	OLE container control contains an embedded object.

vbOLENone	3	OLE container control doesn't contain an object.

OLETypeAllowed Property

Constant	Value	Description

vbOLEEither	2	OLE container control can contain either a linked or an embedded object.

UpdateOptions Property

Constant	Value	Description

vbOLEAutomatic	0	Object is updated each time the linked data changes.

vbOLEFrozen	1	Object is updated whenever the user saves the linked document from within the application in which it was created.

vbOLEManual	2	Object is updated only when the Action property is set to 6 (Update).

AutoActivate Property

Constant	Value	Description

vbOLEActivateManual	0	OLE object isn't automatically activated.

vbOLEActivateGetFocus	1	Object is activated when the OLE container control gets the focus.

vbOLEActivateDoubleclick	2	Object is activated when the OLE container control is double-clicked.

vbOLEActivateAuto	3	Object is activated based on the object's default method of activation.

SizeMode Property

Constant	Value	Description

vbOLESizeClip	0	Object's image is clipped by the OLE container control's borders.

vbOLESizeStretch	1	Object's image is sized to fill the OLE container control.

vbOLESizeAutoSize	2	OLE container control is automatically resized to display the entire object.

vbOLESizeZoom	3	Object's image is stretched but in proportion.

DisplayType Property

Constant	Value	Description

vbOLEDisplayContent	0	Object's data is displayed in the OLE container control.

vbOLEDisplayIcon	1	Object's icon is displayed in the OLE container control.

Updated Event Constants

Constant	Value	Description

vbOLEChanged	0	Object's data has changed.

vbOLESaved	1	Object's data has been saved by the application that created the object.

vbOLEClosed	2	Application file containing the linked object's data has been closed.

vbOLERenamed	3	Application file containing the linked object's data has been renamed.

Special Verb Values

Constant	Value	Description

vbOLEPrimary	0	Default action for the object.

vbOLEShow	-1	Activates the object for editing.

vbOLEOpen	-2	Opens the object in a separate application window.

vbOLEHide	-3	For embedded objects, hides the application that created the object.

vbOLEInPlaceUIActivate	-4	All UI's associated with the object are visible and ready for use.

vbOLEInPlaceActivate	-5	Object is ready for the user to click inside it and start working with it.

vbOLEDiscardUndoState	-6	For discarding all record of changes that the object's application can undo.

Verb Flag Bit Masks

Constant	Value	Description

vbOLEFlagEnabled	0x0	Enabled menu item.

vbOLEFlagGrayed	0x1	Grayed menu item.

vbOLEFlagDisabled	0x2	Disabled menu item.

vbOLEFlagChecked	0x8	Checked menu item.

vbOLEFlagSeparator	0x800	Separator bar in menu item list.

vbOLEMiscFlagMemStorage	0x1	Causes control to use memory to store the object while it's loaded.

vbOLEMiscFlagDisableInPlace	0x2	Forces OLE container control to activate objects in a separate window.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


CommonDialog Control Constants

See Also

File Open/Save Dialog Box Flags

Constant	Value	Description

cdlOFNReadOnly	0x1	Checks Read-Only check box for Open and Save As dialog boxes.

cdlOFNOverwritePrompt	0x2	Causes the Save As dialog box to generate a message box if the selected file already exists.

cdlOFNHideReadOnly	0x4	Hides the Read-Only check box.

cdlOFNNoChangeDir	0x8	Sets the current directory to what it was when the dialog box was invoked.

cdlOFNHelpButton	0x10	Causes the dialog box to display the Help button.

cdlOFNNoValidate	0x100	Allows invalid characters in the returned filename.

cdlOFNAllowMultiselect	0x200	Allows the File Name list box to have multiple selections.

cdlOFNExtensionDifferent	0x400	The extension of the returned filename is different from the extension set by the DefaultExt property.

cdlOFNPathMustExist	0x800	User can enter only valid path names.

cdlOFNFileMustExist	0x1000	User can enter only names of existing files.

cdlOFNCreatePrompt	0x2000	Sets the dialog box to ask if the user wants to create a file that doesn't currently exist.

cdlOFNShareAware	0x4000	Sharing violation errors will be ignored.

cdlOFNNoReadOnlyReturn	0x8000	The returned file doesn't have the Read-Only attribute set and won't be in a write-protected directory.

cdlOFNExplorer	0x0008000	Use the Explorer-like Open A File dialog box template.  (Windows 95 only.)

cdlOFNNoDereferenceLinks	0x00100000	Do not dereference shortcuts (shell links).  By default, choosing a shortcut causes it to be dereferenced by the shell.  (Windows 95 only.)

cdlOFNLongNames	0x00200000	Use Long filenames.  (Windows 95 only.)

Color Dialog Box Flags

Constant	Value	Description

cdlCCRGBInit	0x1	Sets initial color value for the dialog box.

cdlCCFullOpen	0x2	Entire dialog box is displayed, including the Define Custom Colors section.

cdlCCPreventFullOpen	0x4	Disables the Define Custom Colors section of the dialog box.

cdlCCHelpButton	0x8	Dialog box displays a Help button.

Fonts Dialog Box Flags

Constant	Value	Description

cdlCFScreenFonts	0x1	Dialog box lists only screen fonts supported by the system.

cdlCFPrinterFonts	0x2	Dialog box lists only fonts supported by the printer.

cdlCFBoth	0x3	Dialog box lists available screen and printer fonts.

cdlCFHelpButton	0x4	Dialog box displays a Help button.

cdlCFEffects	0x100	Dialog box enables strikeout, underline, and color effects.

cdlCFApply	0x200	Dialog box enables the Apply button.

cdlCFANSIOnly	0x400	Dialog box allows only a selection of fonts that use the Windows character set.

cdlCFNoVectorFonts	0x800	Dialog box should not allow vector-font selections.

cdlCFNoSimulations	0x1000	Dialog box should not allow graphic device interface (GDI) font simulations.

cdlCFLimitSize	0x2000	Dialog box should select only font sizes within the range specified by the Min and Max properties.

cdlCFFixedPitchOnly	0x4000	Dialog box should select only fixed-pitch fonts.

cdlCFWYSIWYG	0x8000	Dialog box should allow only the selection of fonts available to both the screen and printer.

cdlCFForceFontExist	0x10000	 An error dialog box is displayed if a user selects a font or style that doesn't exist.

cdlCFScalableOnly	0x20000	Dialog box should allow only the selection of scalable fonts.

cdlCFTTOnly	0x40000	Dialog box should allow only the selection of TrueType fonts.

cdlCFNoFaceSel	0x80000	No font name selected.

cdlCFNoStyleSel	0x100000	No font style selected.

cdlCFNoSizeSel	0x200000	No font size selected.

Printer Dialog Box Flags

Constant	Value	Description

cdlPDAllPages	0x0	Returns or sets state of All Pages option button.

cdlPDCollate	0x10	Returns or sets state of Collate check box.

cdlPDDisablePrintToFile	0x80000	Disables the Print To File check box.

cdlPDHidePrintToFile	0x100000	The Print To File check box isn't displayed.

cdlPDNoPageNums	0x8	Returns or sets the state of the Pages option button.

cdlPDNoSelection	0x4	Disables the Selection option button.

cdlPDNoWarning	0x80	Prevents a warning message when there is no default printer.

cdlPDPageNums	0x2	Returns or sets the state of the Pages option button.

cdlPDPrintSetup	0x40	Displays the Print Setup dialog box rather than the Print dialog box.

cdlPDPrintToFile	0x20	Returns or sets the state of the Print To File check box.

cdlPDReturnDC	0x100	Returns a device context for the printer selection value returned in the hDC property of the dialog box.

cdlPDReturnDefault	0x400	Returns default printer name.

cdlPDReturnIC	0x200	Returns an information context for the printer selection value returned in the hDC property of the dialog box.

cdlPDSelection	0x1	Returns or sets the state of the Selection option button.

cdlPDHelpButton	0x800	Dialog box displays the Help button.

cdlPDUseDevModeCopies	0x40000	Sets support for multiple copies action; depends upon whether or not printer supports multiple copies.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Help Constants

See Also

Constant	Value	Description

cdlHelpContext	0x1	Displays Help for a particular topic.

cdlHelpQuit	0x2	Notifies the Help application that the specified Help file is no longer in use.

cdlHelpIndex	0x3	Displays the index of the specified Help file.

cdlHelpContents	0x3	Displays the contents topic in the current Help file.

cdlHelpHelpOnHelp	0x4	Displays Help for using the Help application itself.

cdlHelpSetIndex	0x5	Sets the current index for multi-index Help.

cdlHelpSetContents	0x5	Designates a specific topic as the contents topic.

cdlHelpContextPopup	0x8	Displays a topic identified by a context number.

cdlHelpForceFile	0x9	Creates a Help file that displays text in only one font.

cdlHelpKey	0x101	Displays Help for a particular keyword.

cdlHelpCommandHelp	0x102	Displays Help for a particular command.

cdlHelpPartialKey	0x105	Calls the search engine in Windows Help.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


CommonDialog Error Constants

See Also

Constant	Value	Description

cdlAlloc	&H7FF0&	Couldn't allocate memory for FileName or Filter property.

cdlCancel	&H7FF3&	Cancel was selected.

cdlDialogFailure	&H8000&	The function failed to load the dialog box.

cdlFindResFailure	&H7FF9&	The function failed to load a specified resource.

cdlHelp	&H7FEF&	Call to Windows Help failed.

cdlInitialization	&H7FFD&	The function failed during initialization.

cdlLoadResFailure	&H7FF8&	The function failed to load a specified string.

cdlLockResFailure	&H7FF7&	The function failed to lock a specified resource.

cdlMemAllocFailure	&H7FF6&	The function was unable to allocate memory for internal data structures.

cdlMemLockFailure	&H7FF5&	The function was unable to lock the memory associated with a handle.

cdlNoFonts	&H5FFE&	No fonts exist.

cdlBufferTooSmall	&H4FFC&	The buffer at which the member lpstrFile points is too small.

cdlInvalidFileName	&H4FFD&	Filename is invalid.

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

cdlCreateICFailure	&H6FF5&	The PrintDlg function failed when it attempted to create an information context.

cdlDndmMismatch	&H6FF6&	Data in the DevMode and DevNames data structures describe two different printers.

cdlGetDevModeFail	&H6FFA&	The printer device driver failed to initialize a DevMode data structure.

cdlInitFailure	&H6FF9&	The PrintDlg function failed during initialization.

cdlLoadDrvFailure	&H6FFB&	The PrintDlg function failed to load the specified printer's device driver.

cdlNoDefaultPrn	&H6FF7&	A default printer doesn't exist.

cdlNoDevices	&H6FF8&	No printer device drivers were found.

cdlParseFailure	&H6FFD&	The CommonDialog function failed to parse the strings in the [devices] section of WIN.INI.

cdlPrinterCodes	&H6FFF&	The PDReturnDefault flag was set, but either the hDevMode or hDevNames field was nonzero.

cdlPrinterNotFound	&H6FF4&	The [devices] section of WIN.INI doesn't contain an entry for the requested printer.

cdlRetDefFailure	&H6FFC&	The PDReturnDefault flag was set, but either the hDevMode or hDevNames field was nonzero.

cdlSetupFailure	&H6FFE&	Failed to load required resources.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Menu Control Constants

See Also

PopupMenu Method Alignment

Constant	Value	Description

vbPopupMenuLeftAlign	0	Pop-up menu left-aligned.

vbPopupMenuCenterAlign	4	Pop-up menu centered.

vbPopupMenuRightAlign	8	Pop-up menu right-aligned.

PopupMenu Mouse Button Recognition

Constant	Value	Description

vbPopupMenuLeftButton	0	Pop-up menu recognizes left mouse button only.

vbPopupMenuRightButton	2	Pop-up menu recognizes right and left mouse buttons.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Menu Accelerator Constants

See Also

Constant	Value	Description

vbMenuAccelCtrlA	1	User-defined shortcut keystrokes.

vbMenuAccelCtrlB	2	User-defined shortcut keystrokes.

vbMenuAccelCtrlC	3	User-defined shortcut keystrokes.

vbMenuAccelCtrlD	4	User-defined shortcut keystrokes.

vbMenuAccelCtrlE	5	User-defined shortcut keystrokes.

vbMenuAccelCtrlF	6	User-defined shortcut keystrokes.

vbMenuAccelCtrlG	7	User-defined shortcut keystrokes.

vbMenuAccelCtrlH	8	User-defined shortcut keystrokes.

vbMenuAccelCtrlI	9	User-defined shortcut keystrokes.

vbMenuAccelCtrlJ	10	User-defined shortcut keystrokes.

vbMenuAccelCtrlK	11	User-defined shortcut keystrokes.

vbMenuAccelCtrlL	12	User-defined shortcut keystrokes.

vbMenuAccelCtrlM	13	User-defined shortcut keystrokes.

vbMenuAccelCtrlN	14	User-defined shortcut keystrokes.

vbMenuAccelCtrlO	15	User-defined shortcut keystrokes.

vbMenuAccelCtrlP	16	User-defined shortcut keystrokes.

vbMenuAccelCtrlQ	17	User-defined shortcut keystrokes.

vbMenuAccelCtrlR	18	User-defined shortcut keystrokes.

vbMenuAccelCtrlS	19	User-defined shortcut keystrokes.

vbMenuAccelCtrlT	20	User-defined shortcut keystrokes.

vbMenuAccelCtrlU	21	User-defined shortcut keystrokes.

vbMenuAccelCtrlV	22	User-defined shortcut keystrokes.

vbMenuAccelCtrlW	23	User-defined shortcut keystrokes.

vbMenuAccelCtrlX	24	User-defined shortcut keystrokes.

vbMenuAccelCtrlY	25	User-defined shortcut keystrokes.

vbMenuAccelCtrlZ	26	User-defined shortcut keystrokes.

vbMenuAccelF1	27	User-defined shortcut keystrokes.

vbMenuAccelF2	28	User-defined shortcut keystrokes.

vbMenuAccelF3	29	User-defined shortcut keystrokes.

vbMenuAccelF4	30	User-defined shortcut keystrokes.

vbMenuAccelF5	31	User-defined shortcut keystrokes.

vbMenuAccelF6	32	User-defined shortcut keystrokes.

vbMenuAccelF7	33	User-defined shortcut keystrokes.

vbMenuAccelF8	34	User-defined shortcut keystrokes.

vbMenuAccelF9	35	User-defined shortcut keystrokes.

vbMenuAccelF11	36	User-defined shortcut keystrokes.

vbMenuAccelF12	37	User-defined shortcut keystrokes.

vbMenuAccelCtrlF1	38	User-defined shortcut keystrokes.

vbMenuAccelCtrlF2	39	User-defined shortcut keystrokes.

vbMenuAccelCtrlF3	40	User-defined shortcut keystrokes.

vbMenuAccelCtrlF4	41	User-defined shortcut keystrokes.

vbMenuAccelCtrlF5	42	User-defined shortcut keystrokes.

vbMenuAccelCtrlF6	43	User-defined shortcut keystrokes.

vbMenuAccelCtrlF7	44	User-defined shortcut keystrokes.

vbMenuAccelCtrlF8	45	User-defined shortcut keystrokes.

vbMenuAccelCtrlF9	46	User-defined shortcut keystrokes.

vbMenuAccelCtrlF11	47	User-defined shortcut keystrokes.

vbMenuAccelCtrlF12	48	User-defined shortcut keystrokes.

vbMenuAccelShiftF1	49	User-defined shortcut keystrokes.

vbMenuAccelShiftF2	50	User-defined shortcut keystrokes.

vbMenuAccelShiftF3	51	User-defined shortcut keystrokes.

vbMenuAccelShiftF4	52	User-defined shortcut keystrokes.

vbMenuAccelShiftF5	53	User-defined shortcut keystrokes.

vbMenuAccelShiftF6	54	User-defined shortcut keystrokes.

vbMenuAccelShiftF7	55	User-defined shortcut keystrokes.

vbMenuAccelShiftF8	56	User-defined shortcut keystrokes.

vbMenuAccelShiftF9	57	User-defined shortcut keystrokes.

vbMenuAccelShiftF11	58	User-defined shortcut keystrokes.

vbMenuAccelShiftF12	59	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF1	60	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF2	61	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF3	62	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF4	63	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF5	64	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF6	65	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF7	66	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF8	67	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF9	68	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF11	69	User-defined shortcut keystrokes.

vbMenuAccelShiftCtrlF12	70	User-defined shortcut keystrokes.

vbMenuAccelCtrlIns	71	User-defined shortcut keystrokes.

vbMenuAccelShiftIns	72	User-defined shortcut keystrokes.

vbMenuAccelDel	73	User-defined shortcut keystrokes.

vbMenuAccelShiftDel	74	User-defined shortcut keystrokes.

vbMenuAccelAltBksp	75	User-defined shortcut keystrokes.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


Printer Object Constants

See Also

Printer Color Mode

Constant	Value	Description

vbPRCMMonochrome	1	Monochrome output.

vbPRCMColor	2	Color output.

Duplex Printing

Constant	Value	Description

vbPRDPSimplex	1	Single-sided printing.

vbPRDPHorizontal	2	Double-sided horizontal printing.

vbPRDPVertical	3	Double-sided vertical printing.

Printer Orientation

Constant	Value	Description

vbPRORPortrait	1	Documents print with the top at the narrow side of the paper.

vbPRORLandscape	2	Documents print with the top at the wide side of the paper.

Print Quality

Constant	Value	Description

vbPRPQDraft	-1	Draft print quality.

vbPRPQLow	-2	Low print quality.

vbPRPQMedium	-3	Medium print quality.

vbPRPQHigh	-4	High print quality.

PaperBin Property

Constant	Value	Description

vbPRBNUpper	1	Use paper from the upper bin.

vbPRBNLower	2	Use paper from the lower bin.

vbPRBNMiddle	3	Use paper from the middle bin.

vbPRBNManual	4	Wait for manual insertion of each sheet of paper.

vbPRBNEnvelope	5	Use envelopes from the envelope feeder.

vbPRBNEnvManual	6	Use envelopes from the envelope feeder, but wait for manual insertion.

vbPRBNAuto	7	(Default) Use paper from the current default bin.

vbPRBNTractor	8	Use paper fed from the tractor feeder.

vbPRBNSmallFmt	9	Use paper from the small paper feeder.

vbPRBNLargeFmt	10	Use paper from the large paper bin.

vbPRBNLargeCapacity	11	Use paper from the large capacity feeder.

vbPRBNCassette	14	Use paper from the attached cassette cartridge.

PaperSize Property

Constant	Value	Description

vbPRPSLetter	1	Letter, 8 1/2 x 11 in.

vbPRPSLetterSmall	2	+A611Letter Small, 8 1/2 x 11 in.

vbPRPSTabloid	3	Tabloid, 11 x 17 in.

vbPRPSLedger	4	Ledger, 17 x 11 in.

vbPRPSLegal	5	Legal, 8 1/2 x 14 in.

vbPRPSStatement	6	Statement, 5 1/2 x 8 1/2 in.

vbPRPSExecutive	7	Executive, 7 1/2 x 10 1/2 in.

vbPRPSA3	8	A3, 297 x 420 mm.

vbPRPSA4	9	A4, 210 x 297 mm.

vbPRPSA4Small	10	A4 Small, 210 x 297 mm.

vbPRPSA5	11	A5, 148 x 210 mm.

vbPRPSB4	12	B4, 250 x 354 mm.

vbPRPSB5	13	B5, 182 x 257 mm.

vbPRPSFolio	14	Folio, 8 1/2 x 13 in.

vbPRPSQuarto	15	Quarto, 215 x 275 mm.

vbPRPS10x14	16	10 x 14 in.

vbPRPS11x17	17	11 x 17 in.

vbPRPSNote	18	Note, 8 1/2 x 11 in.

vbPRPSEnv9	19	Envelope #9, 3 7/8 x 8 7/8 in.

vbPRPSEnv10	20	Envelope #10, 4 1/8 x 9 1/2 in.

vbPRPSEnv11	21	Envelope #11, 4 1/2 x 10 3/8 in.

vbPRPSEnv12	22	Envelope #12, 4 1/2 x 11 in.

vbPRPSEnv14	23	Envelope #14, 5 x 11 1/2 in.

vbPRPSCSheet	24	C size sheet.

vbPRPSDSheet	25	D size sheet.

vbPRPSESheet	26	E size sheet.

vbPRPSEnvDL	27	Envelope DL, 110 x 220 mm.

vbPRPSEnvC3	29	Envelope C3, 324 x 458 mm.

vbPRPSEnvC4	30	Envelope C4, 229 x 324 mm.

vbPRPSEnvC5	28	Envelope C5, 162 x 229 mm.

vbPRPSEnvC6	31	Envelope C6, 114 x 162 mm.

vbPRPSEnvC65	32	Envelope C65, 114 x 229 mm.

vbPRPSEnvB4	33	Envelope B4, 250 x 353 mm.

vbPRPSEnvB5	34	Envelope B5, 176 x 250 mm.

vbPRPSEnvB6	35	Envelope B6, 176 x 125 mm.

vbPRPSEnvItaly	36	Envelope, 110 x 230 mm.

vbPRPSEnvMonarch	37	Envelope Monarch, 3 7/8 x 7 1/2 in.

vbPRPSEnvPersonal	38	Envelope, 3 5/8 x 6 1/2 in.

vbPRPSFanfoldUS	39	U.S. Standard Fanfold, 14 7/8 x 11 in.

vbPRPSFanfoldStdGerman	40	German Standard Fanfold, 8 1/2 x 12 in.

vbPRPSFanfoldLglGerman	41	German Legal Fanfold, 8 1/2 x 13 in.

vbPRPSUser	256	User-defined.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


RasterOp Constants

See Also

Constant	Value	Description

vbDstInvert	0x00550009	Inverts the destination bitmap.

vbMergeCopy	0x00C000CA	Combines the pattern and the source bitmap.

vbMergePaint	0x00BB0226	Combines the inverted source bitmap with the destination bitmap by using Or.

vbNotSrcCopy	0x00330008	Copies the inverted source bitmap to the destination.

vbNotSrcErase	0x001100A6	Inverts the result of combining the destination and source bitmaps by using Or.

vbPatCopy	0x00F00021L	Copies the pattern to the destination bitmap.

vbPatInvert	0x005A0049L	Combines the destination bitmap with the pattern by using Xor.

vbPatPaint	0x00FB0A09L	Combines the inverted source bitmap with the pattern by using Or.  Combines the result of this operation with the destination bitmap by using Or.

vbSrcAnd	0x008800C6	Combines pixels of the destination and source bitmaps by using And.

vbSrcCopy	0x00CC0020	Copies the source bitmap to the destination bitmap.

vbSrcErase	0x00440328	Inverts the destination bitmap and combines the result with the source bitmap by using And.

vbSrcInvert	0x00660046	Combines pixels of the destination and source bitmaps by using Xor.

vbSrcPaint	0x00EE0086	Combines pixels of the destination and source bitmaps by using Or.


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants


VBTranslateColor/OLETranslateColor Constants

See Also

Constant	Value	Description

vbInactiveCaptionText	0x80000013	Color of text in an inactive caption.

vb3DHighlight	0x80000014	Highlight color for 3-D display elements.

vb3DFace	0x8000000F	Dark shadow color for 3-D display elements.

vbMsgBox	0x80000017	Background color for message boxes and system dialog boxes.

vbMsgBoxText	0x80000018	Color of text displayed in message boxes and system dialog boxes.

vb3DShadow	0x80000010	Color of automatic window shadows.

vb3DDKShadow	0x80000015	Darkest shadow.

vb3DLight	0x80000016	Second lightest of the 3-D colors (after vb3DHighlight).


See Also

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

Data Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Control Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants


Visual Basic Constants

See Also

The following constants are specified or recognized by Visual Basic.  As a result, they can be used anywhere in your code in place of the actual values.

Alignment Constants

Border Property Constants

Clipboard Object Constants

Color Constants

CommonDialog Control Constants

CommonDialog Error Constants

Control Constants

Data Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants

DDE Constants

Drag-and-Drop Constants

Drawing Constants

Form Constants

Graphics Constants

Grid Control Constants

Help Constants

Key Code Constants

Menu Accelerator Constants

Menu Control Constants

Miscellaneous Constants

Mouse Pointer Constants

OLE Container Control Constants

Picture Object Constants

Printer Object Constants

RasterOp Constants

Variant Type Constants

VBTranslateColor/OLETranslateColor Constants

Use the Object Browser to view the intrinsic constants you can use with methods and properties.  From the View menu, choose Object Browser, select the Visual Basic object library, and then choose the Constants object.  You can scroll through the constants that appear under Methods/Properties.


See Also

Visual Basic for Applications Constants

Data Access Constants


access key <definition>
access key

A key pressed while holding down the ALT key that allows the user to open a menu, carry out a command, select an object, or move to an object.  For example, ALT+F opens the File menu.


active window <definition>
active window

The window that appears in the foreground with a highlighted title bar or border to distinguish it from other visible windows.


add-in <definition>
add-in

A customized tool that adds capabilities to the Visual Basic development environment.  You select available add-ins using the Add-In Manager dialog box accessible from the Add-Ins menu.


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.


assignment statement <definition>
assignment statement

A statement such as Text1.Text = "My Name" that assigns a value to a variable or property.  You must use the Set statement to assign an object reference.


binary format <definition>
binary format

Machine-readable form.  This format is different from ASCII or ANSI formats, which encode data as text.


bit <definition>
bit

Binary digit: the smallest unit of data a computer can store.  Bits are expressed as 1 or 0.


bitmap <definition>
bitmap

An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel.  On color systems, more than one bit corresponds to each pixel.  A bitmap usually has a .BMP filename extension.


bitmask <definition>
bitmask

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.


Calls button <definition>
Calls button

A debugging tool on the toolbar that, when clicked during break mode, presents a dialog box that lists all called procedures that have not run to completion.


Cancel button <definition>
Cancel button

A button you choose to cancel changes.  This is also a generic term for any command button on a form that has the Cancel property set to True, allowing the user to press ESC or to click the button to cancel changes on that form.


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.  Cascading event procedures often result in run-time errors, such as stack overflow.


check box <definition>
check box

A control (CheckBox) used to represent an option (on/off, True/False) that the user can set or clear by clicking.  An X in a check box indicates it is selected, set to on, or has a value of True.


collection syntax <definition>
collection syntax

For a Things collection that contains Thing objects, the collection itself would be referred to as

object.Things

while an individual Thing object would be referred to as

object.Things.Item(index)

or

object.Things(index)

where index is an integer denoting a specific element in the collection.


compile error <definition>
compile error

An error that occurs during compile time as the result of incorrectly constructed code.


compound document file <definition>
compound document file

A file that can contain data in different formats, for example, as spreadsheets, text, and bitmaps.


container <definition>
container

An object that contains child forms or controls.


control <definition>
control

An object you can place on a form that has its own set of recognized properties and events.  You use controls to receive user input, display output, and 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 array <definition>
control array

A group of controls that share a common name, type, and event procedures.  Each control in the array has a unique index number that can be used to determine which control recognizes an event.


Control-menu commands <definition>
Control-menu commands

Commands that allow you to move or resize the title bar, switch to other Windows-based applications, or close the current application.


controlling application <definition>
controlling application

An application, for example Visual Basic, that uses objects provided by OLE servers.  Also called an OLE Automation controller.


cross hair <definition>
cross hair

A cross-shaped pointer displayed when you select a control from the Toolbox and move the mouse over a form.  For the MousePointer property, this pointer setting is called Cross.


custom control <definition>
custom control

A file with a .VBX or .OCX filename extension or an insertable object that, when added to a project using the Custom Controls dialog box, extends the Toolbox.  The CommonDialog and DBCombo controls are examples of custom controls.


default color box <definition>
default color box

A box in the Color palette that displays the currently selected foreground and background colors for the form or control.


destination <definition>
destination

In an active link of a dynamic data exchange (DDE), the application, form, or control that requests data from the source application.


device context <definition>
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 <definition>
dialog box

A special window displayed by the system or application to solicit a response from or provide information to the user.


drag-and-drop operation <definition>
drag-and-drop operation

A combination of features that allow the user to drag an object and drop it onto a form or other object 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 <definition>
editing key

The INSERT, DELETE, or BACKSPACE key.


embedded object <definition>
embedded object

An object that is created in another application and then embedded in a Visual Basic application.  When you create an embedded object, all the data associated with the object is copied to and contained in the Visual Basic application.


error trapping <definition>
error trapping

The process of intercepting an error using error-handling features in Visual Basic.


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 a 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 system.  Event procedures are private by default.


executable file <definition>
executable file

A Windows-based application that can run outside the development environment.  An executable file has an .EXE filename extension.


flag <definition>
flag

A variable you use to keep track of a condition in your application.  You can set a flag using a constant or combination of constants.


form <definition>
form

A window or dialog box.  Forms are containers for controls.  A multiple-document interface (MDI) form can also act as a container for child forms and some controls.


form module <definition>
form module

A file in a Visual Basic project with an .FRM filename extension that can contain graphical descriptions of a form; its controls and their property settings; form-level declarations of constants, variables, and external procedures; and event and general procedures.


function key <definition>
function key

Any of the keys labeled F1 through F16.  Function keys often provide shortcuts for frequently carried out commands and actions.  You can assign a function key as a shortcut key.


Function procedure <definition>
Function procedure

A procedure that performs a specific task within a Visual Basic program and returns a value.  A Function procedure begins with a Function statement and ends with an End Function statement.


general procedure <definition>
general procedure

A procedure that must be explicitly called by another procedure.  In contrast, an event procedure is invoked automatically in response to a user or system action.


graphics method <definition>
graphics method

A method that operates on an object such as a Form, PictureBox, or Printer, and performs run-time drawing operations such as animation or simulation.  The graphics methods are Circle, Cls, Line, PaintPicture, Point, Print, and PSet.


handle <definition>
handle

A unique integer value defined by the operating environment and used by a program to identify and access an object, such as a form or control.


icon <definition>
icon

A graphical representation of an object or concept; commonly used to represent minimized applications in Microsoft Windows.  Essentially, an icon is a bitmap with a maximum size of 32 x 32 pixels.  Icons have an .ICO filename extension.


Immediate pane

A pane in the Debug window that displays information resulting from debugging statements in your code or from commands typed directly into the pane.


in-place activation <definition>
in-place activation

The process of activating an object provided by an OLE server.  By double-clicking the object, a user can interact with the application supplying the object without switching to a different application or window.  Also called visual editing.


index <definition>
index

A number that identifies an element in an array, control array, or collection.


insertable object <definition>
insertable object

An object of an application, such as a Microsoft Excel Worksheet, that is a type of custom control.  You can add this object to the Toolbox using the Custom Controls dialog box.


instance <definition>
instance

Any one of a set of objects sharing the same class.  For example, multiple instances of a Form class share the same code and are loaded with the same controls with which the Form class was designed.  During run time, the individual properties of controls on each instance can be set to different values.


internal area <definition>
internal area

The area in a multiple-document interface (MDI) form used to display MDI child forms.  The internal area excludes the MDI form's title bar, border, menu bar, and aligned controls on the MDI form.  Also called the client area.


intrinsic constant <definition>
intrinsic constant

A constant provided by an application.  Visual Basic constants are listed in the Visual Basic (VB) object library and can be viewed using the Object Browser.


linked object <definition>
linked object

An object that is created in another application and linked to a Visual Basic application.  When you link an object, you insert a placeholder in your application.  Unlike an embedded object, a linked object's data is actually stored in and managed by the application that created it.


list box <definition>
list box

A control (ListBox) that displays a list of choices.


master copy

The most recent version of a file stored in the version control program's database, as opposed to the local copy of a file in your working directory.


Maximize button <definition>
Maximize button

A button in the upper-right corner of a window that enlarges the window to fill the entire screen.


MDI child <definition>
MDI child

A form contained within an MDI form in a multiple-document interface (MDI) application.  To create a child form, set its MDIChild property to True.


MDI form <definition>
MDI form

A window that makes up the background of a multiple-document interface (MDI) application.  The MDI form is the container for any MDI child forms in the application.


memory object <definition>
memory object

A block of memory allocated using the Windows API GlobalAlloc() that contains data in a format indicated by the Format property setting of the OLE container control.


metafile <definition>
metafile

A file that stores an image as graphical objects (lines, circles, polygons) rather than as pixels.  There are two types of metafiles, standard and enhanced.  Standard metafiles usually have a .WMF filename extension.  Enhanced metafiles usually have a .EMF filename extension.  Metafiles preserve an image more accurately than pixels when the image is resized.


Minimize button <definition>
Minimize button

A button in the upper-right corner of a window that shrinks the window to an icon.


modal <definition>
modal

Describes a window or dialog box that requires the user to take some action before the focus can switch to another form or dialog box.


modeless <definition>
modeless

Describes a window or dialog box that does not require user action before the focus can be switched to another form or dialog box.


object <definition>
object

A combination of code and data that can be treated as a unit, for example a control, form, or application.  Each object is defined by a class.


OLE server <definition>
OLE server

An application that provides its objects to other applications.  You can use any of these objects in your Visual Basic application.  Also called an OLE Automation server.


Object box <definition>
Object box

  A list box at the upper-left corner of the Code window that lists the form 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.


object variable <definition>
object variable

A variable that contains a reference to an object.


OLE <definition>
OLE

Object linking and embedding: The technology that enables you to create applications that contain components from various other applications.


OLE Automation <definition>
OLE Automation

A technology that enables applications to provide objects in a consistent way to other applications, development tools, and macro languages.


OLE Automation controller <definition>
OLE Automation controller

An application, for example Visual Basic, that uses objects provided by OLE servers.  Also called a controlling application.


OLE custom control <definition>
OLE custom control

A file in a Visual Basic project with an .OCX filename extension that is associated with a visible interface. The Grid and CommonDialog controls are examples of OLE custom controls.


option button <definition>
option button

A control (OptionButton) used to display an option or, more typically, a group of related options from which you can select only one.


parent form <definition>
parent form

A form containing controls.


Paste Link command <definition>
Paste Link command

A command that inserts Clipboard contents copied from one Windows-based application to another.  This command creates a link between the applications so that copied data is updated automatically.


pen <definition>
pen

The graphical characteristics, such as color, specified by a Line, Point, or Circle statement or by the current ForeColor or FillColor setting.


persistent bitmap <definition>
persistent graphic

The output from a graphics method that is stored in memory.  Persistent graphics are automatically retained when certain kinds of screen events occur, for example, when a form is redisplayed after being hidden behind another window.  Graphics are persistent if they are drawn when the AutoRedraw property is set to True.


pixel <definition>
pixel

Short for 'picture element,' a dot that represents the smallest graphic unit of measurement on a screen.  A pixel is screen-dependent; that is, the dimensions of screen elements vary with the display system and resolution.


point <definition>
point

In typesetting, a point is 1/72 of an inch.  The height of fonts is usually expressed in points.


poke <definition>
poke

In dynamic data exchange (DDE), to send data from a destination application to a source application.  A form's LinkMode property must be set to Source to allow a destination application to send data to controls on the form.


pop-up menu <definition>
pop-up menu

A floating menu that is displayed over a form, independent of the menu bar.  Clicking the right mouse button usually causes a pop-up menu to be displayed.  The items on the menu depend on the pointer location when the menu is displayed.  Also called a context menu.


Procedure box <definition>
Procedure box

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


procedure call <definition>
procedure call

A statement in code that tells Visual Basic to execute a procedure.


procedure template <definition>
procedure template

The beginning and ending statements that are automatically inserted in the Code window when you specify a Sub, Function, or Property procedure in the Insert Procedure dialog box.


project

A logical grouping of related files, typically all the files required to develop a software component.  Files can be grouped within a project to create child projects.  Projects can be defined in any way meaningful to the user(s)as one project per version, or one project per language, for example.  In general use, projects tend to be organized in the same way file directories are.


project file <definition>
project file

A file with a .VBP filename extension that keeps track of the files, objects, project options, environment options, EXE options , and references associated with a project.


Project window <definition>
Project window

A window that displays a list of the form, class, and standard modules; the resource file; and references in your project.  Files with .OCX and .VBX filename extensions don't appear in this window.


Properties button <definition>
Properties button

A button displayed to the right of a property in the Properties window.  Click this button to display all the settings for a specific property.


Properties window <definition>
Properties window

A window used to display or change properties of a selected form or control at design time.  Some custom controls have customized Properties windows.


Property list <definition>
Property list

A two-column list in the Properties window that shows all the properties and their current settings for the selected object.


Property procedure <definition>
Property procedure

A procedure that creates and manipulates properties for a class module.  A Property procedure begins with a Property Let, Property Get, or Property Set statement and ends with an End Property statement.


read-only file

A file marked as read-only in its file attributes.  Such a file can be viewed in an appropriate text editor, but cannot be modified.  The version control program generally marks the file as read-only during check in and when you use the Get command.


recursion <definition>
recursion

The process that occurs when a procedure calls itself.  Uncontrolled recursion usually results in an Out of stack space error message.


resource file <definition>
resource file

A file in a Visual Basic project with an .RES filename extension that can contain bitmaps, text strings, or other data.  By putting this data in a separate file, you can change the information without having to re-edit your code.  Only one resource file can be associated with a project.


separator bar <definition>
separator bar

A bar that divides commands into logical groups on a menu.


shadowing <definition>
shadowing

The act of being accessed in preference to something else.  For example, when two variables have the same name but different scopes, the more local variable always shadows the less local variable.


shortcut key <definition>
shortcut key

A function key or key combination (such as F5 or CTRL+A) that executes a command.  You can set shortcut keys in the Menu Editor.


source <definition>
source

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


split bar <definition>
split bar

The thin bar that divides a Code or Debug window into two separate areas called panes.  In the Debug window, the split bar separates the Immediate pane from the Watch pane.


stack <definition>
stack

A fixed amount of memory used by Visual Basic to preserve local variables and arguments during procedure calls.


standard control <definition>
standard control

A control included in the Toolbox and contained within the Visual Basic .EXE file; for example, a CommandButton or Frame control.  Standard controls are always included in the Toolbox, unlike custom controls or insertable objects, which can be removed from or added to the Toolbox.


startup form <definition>
startup form

The first form displayed in your application, which is usually the first form you create in the development environment.  You can change the startup form using the Startup Form option on the Project Options dialog box.


Static <definition>
Static

A Visual Basic keyword you can use to preserve the value of a local variable.


Sub procedure <definition>
Sub procedure

A procedure that performs a specific task within a program, but returns no explicit value.  A Sub procedure begins with a Sub statement and ends with an End Sub statement.


submenu <definition>
submenu

A menu opened from another menu that displays its own list of commands.


syntax <definition>
syntax

The prescribed order and punctuation for putting programming language elements into statements that are meaningful to Visual Basic.


system modal <definition>
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 can't switch to any other form or dialog in any other running applications.


tab order <definition>
tab order

The order in which the focus moves among controls on a form as the user presses the TAB or SHIFT+TAB key.  Unless you change this order with the TabIndex property, the tab order reflects the order in which you created the controls.


twip <definition>
twip

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.  A twip is a unit of screen measurement equal to 1/20 of a printer's point.  There are approximately 1440 twips to a logical inch or 567 twips to a logical centimeter (the length of a screen item measuring one inch or one centimeter when printed).


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.


Unicode <definition>
Unicode

A character-encoding scheme that uses 2 bytes for every character regardless of whether or not it is an ASCII character.  This scheme is supported by the Microsoft Windows NT platform and used by 32-bit OLE technology.


user-interface negotiation <definition>
user-interface negotiation

The process of placing the menus and toolbars of a Visual Basic application (or OLE Automation controller) and those of an OLE server together on a container form.


verb <definition>
verb

Specifies an action that can be performed on an object, such as Edit.


visual editing <definition>
visual editing

The process of activating an object provided by an OLE server.  By double-clicking the object on a container form, a user can interact with the application supplying the object without switching to a different application or window.  Also called in-place activation.


Watch pane <definition>
Watch pane

An upper pane in the Debug window that displays the current watch expressions and the procedure or modules(s) in which you are evaluating each watch expression.


Windows API <definition>
Windows API

The Windows API (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.  These include 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).


Windows OpenFile function <definition>
Windows OpenFile function

The Windows OpenFile function searches for a matching file in the following directories in the following order:

1.	The current directory.

2.	The Windows directory, whose path the GetWindowsDirectory function retrieves.

3.	The Windows system directory, whose path the GetSystemDirectory function retrieves.

4.	The directory containing the executable file for the current task; the GetModuleFileName function obtains the path of this directory.

5.	The directories listed in the PATH environment variable.

6.	The list of directories mapped in a network.


working directory

A specified directory on your local computer used to store files when they are checked out of the version control program's database. You make changes to files in the working directory, then check the modified files back into the version control program for version tracking.


z-order <definition>
z-order

The relative order that determines how controls overlap each other on a form.


Activate, Deactivate Events

See Also	Example	Applies To

Activate [image] occurs when a form becomes the active window.

Deactivate [image] occurs when a form is no longer the active window.

Syntax

Private Sub object_Activate( )

Private Sub object_Deactivate( )

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

A form can become active by user action, such as clicking the form, 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 isn't 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 doesn't trigger either event.  The Deactivate event doesn't 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 MDIForm object 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 MDIForm receives the Activate and Deactivate events.


See Also

GotFocus Event

LostFocus Event

SetFocus Method

Show Method

Visible Property


Activate, Deactivate Events Apply To

Form Object

MDIForm Object


Change Event

See Also	Example	Applies To

Indicates that the contents of a control have changed.  How and when this event occurs varies with the control:

ComboBox [image] changes the text in the text box portion of the control.  Occurs only if the Style property is set to 0 (Dropdown Combo) or 1 (Simple Combo) and the user changes the text or you change the Text property setting through code.

DirListBox [image] changes the selected directory.  Occurs when the user double-clicks a new directory or when you change the Path property setting through code.

DriveListBox [image] changes the selected drive.  Occurs when the user selects a new drive or when you change the Drive property setting through code.

HScrollBar and VScrollBar (horizontal and vertical scroll bars) [image] move the scroll box portion of the scroll bar.  Occurs when the user scrolls or when you change the Value property setting through code.

Label [image] changes the contents of the Label.  Occurs when a DDE link updates data or when you change the Caption property setting through code.

PictureBox [image] changes the contents of the PictureBox.  Occurs when a DDE link updates data or when you change the Picture property setting through code.

TextBox [image] changes the contents of the text box.  Occurs when a DDE link updates data, when a user changes the text, or when you change the Text property setting through code.

Syntax

Private Sub object_Change([index As Integer])

The Change event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

The Change event procedure can synchronize or coordinate data display among controls.  For example, you can use a scroll bar's Change event procedure to update the scroll bar's Value property setting in a TextBox control.  Or you can use a Change event procedure to display data and formulas in a work area and results in another area.

Change event procedures are also useful for updating properties in file-system controls (DirListBox, DriveListBox, and FileListBox).  For example, you can update the Path property setting for a DirListBox control to reflect a change in a DriveListBox control's Drive property setting.

Note   A Change event procedure can sometimes cause a cascading event.  This occurs when the control's Change event alters the control's contents, for example, by setting a property in code that determines the control's value, such as the Text property setting for a TextBox control.  To prevent a cascading event:

If possible, avoid writing a Change event procedure for a control that alters that control's contents.  If you do write such a procedure, be sure to set a flag that prevents further changes while the current change is in progress.

Avoid creating two or more controls whose Change event procedures affect each other, for example, two TextBox controls that update each other during their Change events.

Avoid using a MsgBox function or statement in this event for HScrollBar and VScrollBar controls.


See Also

Caption Property

Drive Property

KeyDown, KeyUp Events

KeyPress Event

LinkTopic Property

LostFocus Event

Path Property

PathChange Event

PatternChange Event

Picture Property

Style Property

Text Property

Value Property


Change Event Applies To

ComboBox Control

DBCombo Control

DBGrid Control

DirListBox Control

DriveListBox Control

HScrollBar, VScrollBar Controls

Label Control

PictureBox Control

TextBox Control


Click Event

See Also	Example	Applies To

Occurs when the user presses and then releases a mouse button over an object.  It can also occur when the value of a control is changed.

For a Form object, 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 CheckBox, CommandButton, or OptionButton control, the Click event occurs only when the user clicks the left mouse button.

Selects an item in a ComboBox or ListBox control, either by pressing the arrow keys or by clicking the mouse button.

Presses the SPACEBAR when a CommandButton, OptionButton, or CheckBox control has the focus.

Presses ENTER when a form has a CommandButton control with its Default property set to True.

Presses ESC when a form has a Cancel button [image] a CommandButton control with its Cancel property set to True.

Presses an access key for a control.  For example, if the caption of a CommandButton control is "&Go", pressing ALT+G triggers the event.

You can also trigger the Click event in code by:

Setting a CommandButton control's Value property to True.

Setting an OptionButton control's Value property to True.

Changing a CheckBox control's Value property setting.

Syntax

Private Sub Form_Click( )

Private Sub object_Click([index As Integer])

The Click event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

Typically, you attach a Click event procedure to a CommandButton control, Menu object, or PictureBox control 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 the state of the control from code.  Clicking a control generates MouseDown and MouseUp events in addition to the Click event.  The order in which these three events occur varies from control to control.  For example, for ListBox and CommandButton controls, the events occur in this order: MouseDown, Click, MouseUp.  But for FileListBox, Label, or PictureBox controls, the events occur in this order: MouseDown, MouseUp, and Click.  When you're attaching event procedures for these related events, be sure that their actions don't conflict.  If the order of events is important in your application, test the control to determine the event order.

Note   To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.


See Also

Cancel Property

DblClick Event

Default Property

MouseDown, MouseUp Events

Value Property


Click Event Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Image Control

Label Control

ListBox Control

Menu Object

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


DragDrop Event

See Also	Example	Applies To

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 set to 2 (Drop).

Syntax

Private Sub Form_DragDrop(source As Control, x As Single, y As Single)

Private Sub MDIForm_DragDrop(source As Control, x As Single, y As Single)

Private Sub object_DragDrop([index As Integer,]source As Control, x As Single, y As Single)

The DragDrop event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

source	The control being dragged.  You can include properties and methods with this argument [image] for example, Source.Visible = 0.

x, y	A number that specifies 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.

Remarks

Use a DragDrop event procedure to control what happens after a drag operation is 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 keyword 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 event 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 event procedure.


See Also

Drag Method

DragIcon Property

DragMode Property

DragOver Event

MouseDown, MouseUp Events

MouseMove Event


DragDrop Event Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

OptionButton Control

PictureBox Control

TextBox Control


DragOver Event

See Also	Example	Applies To

Occurs when a drag-and-drop operation is in progress.  You can use this event to monitor the mouse pointer as it enters, leaves, or rests directly over a valid target.  The mouse pointer position determines the target object that receives this event.

Syntax

Private Sub Form_DragOver(source As Control, x As Single, y As Single, state As Integer)

Private Sub MDIForm_DragOver(source As Control, x As Single, y As Single, state As Integer)

Private Sub object_DragOver([index As Integer,]source As Control, x As Single, y As Single, state As Integer)

The DragOver event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's 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	A number that specifies 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	An integer that corresponds to 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).

Remarks

Use a DragOver event procedure to determine what happens after dragging is initiated and before a control drops onto a target.  For example, you can 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 state argument to determine actions at key transition points.  For example, you might highlight a possible target when state is set to 0 (Enter) and restore the object's previous appearance when state is set to 1 (Leave).

When an object receives a DragOver event when state is set to 0 (Enter):

If the source control is dropped on the object, that object receives a DragDrop event.

If the source control isn't dropped on the object, that object receives another DragOver event when state is set to 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 Remarks for the DragDrop event topic.


See Also

Drag Method

DragDrop Event

DragIcon Property

DragMode Property

MouseDown, MouseUp Events

MouseMove Event

MouseUp Event


DragOver Event Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

OptionButton Control

PictureBox Control

TextBox Control


DropDown Event

See Also	Example	Applies To

Occurs when the list portion of a ComboBox control is about to drop down; this event doesn't occur if a ComboBox control's Style property is set to 1 (Simple Combo).

Syntax

Private Sub object_DropDown([index As Integer])

The DropDown event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

Use a DropDown event procedure to make final updates to a ComboBox list before the user makes a selection.  This enables 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 ComboBox list depends on what the user selects in an OptionButton group.


See Also

Style Property


DropDown Event Applies To

ComboBox Control


GotFocus Event

See Also	Example	Applies To

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.  A form receives the focus only when all visible controls are disabled.

Syntax

Private Sub Form_GotFocus( )

Private Sub object_GotFocus([index As Integer])

The GotFocus event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

Typically, you use a GotFocus event procedure to specify the actions that occur when a control or form first receives the focus.  For example, by attaching a GotFocus event 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 the keyboard interface in Visual Basic for moving the focus, set the tab order or specify access keys for controls on a form.


See Also

ActiveControl Property

ActiveForm Property

LostFocus Event

SetFocus Method

TabIndex Property

TabStop Property


GotFocus Event Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


KeyDown, KeyUp Events

See Also	Example	Applies To

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

Private Sub Form_KeyDown(keycode As Integer, shift As Integer)

Private Sub object_KeyDown([index As Integer,]keycode As Integer, shift As Integer)

Private Sub Form_KeyUp(keycode As Integer, shift As Integer)

Private Sub object_KeyUp([index As Integer,]keycode As Integer, shift As Integer)

The KeyDown and KeyUp event syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

keycode	A key code, such as vbKeyF1 (the F1 key) or vbKeyHome (the HOME key).  To specify key codes, use the constants in the Visual Basic (VB) object library in the Object Browser.

shift	An integer that corresponds to 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 are pressed.  For example, if both CTRL and ALT are pressed, the value of shift is 6.

Remarks

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 the KeyDown and KeyUp events can apply to most keys, they're 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 if you need to respond to both the pressing and releasing of a key.

KeyDown and KeyUp aren't invoked for:

The ENTER key if the form has a CommandButton control with the Default property set to True.

The ESC key if the form has a CommandButton control with the Cancel property set to True.

The TAB key.

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 you need to test for the shift argument, you can declare constants that define the bits within the argument by using constants listed in the Visual Basic (VB) object library in the Object Browser.  The shift constants have the following values:

Constant	Value	Description

vbShiftMask	1	SHIFT key bit mask.

vbCtrlMask	2	CTRL key bit mask.

vbAltMask	4	ALT key bit mask.

The constants act as bit masks that you can use to test for any combination of keys.  Place the constants at the procedure level or in the Declarations section of a module and use this syntax:

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, as in this example:

ShiftDown = (Shift And vbShiftMask) > 0

In a procedure, you can test for any combination of conditions, as in this example:

If ShiftDown And CtrlDown Then

Note   If the KeyPreview property is set to 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

KeyPreview Property

Operator Precedence

SendKeys Statement


KeyDown, KeyUp Events Apply To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

OptionButton Control

PictureBox Control

TextBox Control


KeyPress Event

See Also	Example	Applies To

Occurs when the user presses and releases an ANSI key.

Syntax

Private Sub Form_KeyPress(keyascii As Integer)

Private Sub object_KeyPress([index As Integer,]keyascii As Integer)

The KeyPress event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

keyascii	An integer that 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 the object receives no character.

Remarks

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 set to 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 TextBox or ComboBox control.  It enables you to immediately test keystrokes for validity or to format characters as they're typed.  Changing the value of the keyascii argument changes the character displayed.

You can convert the keyascii argument 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 interpret 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 doesn't indicate the physical state of the keyboard; instead, it passes a character.

KeyPress interprets the uppercase and lowercase of each character as separate key codes 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 set to 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 zero-length string (""), avoid using CTRL+@ in your applications.


See Also

Asc Function

Change Event

Character Set (0 - 127)

Character Set (128 - 255)

Chr Function

KeyDown, KeyUp Events

KeyPreview Property

SendKeys Statement


KeyPress Event Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

OptionButton Control

PictureBox Control

TextBox Control


LinkClose Event

See Also	Applies To

Occurs when a DDE conversation terminates.  Either application in a DDE conversation may terminate a conversation at any time.

Syntax

Private Sub Form_LinkClose( )

Private Sub MDIForm_LinkClose( )

Private Sub object_LinkClose([index As Integer])

The LinkClose event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

Typically, you use a LinkClose event procedure to notify the user that a DDE conversation has been terminated.  You can also include troubleshooting information on reestablishing a connection or where to go for assistance.  For brief messages, use the MsgBox function.


See Also

LinkError Event

LinkExecute Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property


LinkClose Event Applies To

Form Object

Label Control

MDIForm Object

PictureBox Control

TextBox Control


LinkError Event

See Also	Example	Applies To

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

Private Sub Form_LinkError(linkerr As Integer)

Private Sub MDIForm_LinkError(linkerr As Integer)

Private Sub object_LinkError([index As Integer,]linkerr As Integer)

The LinkError event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

linkerr	Error number of the DDE-related error, as described in Return Values.

index	An integer that uniquely identifies a control if it's in a control array.

Return Values

The following table lists all error numbers returned for the linkerr argument and a brief explanation of each error:

Value	Description

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 a DDE conversation after you set the LinkMode property 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.

Remarks

Use a LinkError event procedure to notify the user of the particular error that has occurred.  You can 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.


See Also

LinkClose Event

LinkExecute Event

LinkExecute Method

LinkItem Property

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property


LinkError Event Applies To

Form Object

Label Control

MDIForm Object

PictureBox Control

TextBox Control


LinkExecute Event

See Also	Example	Applies To

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

Private Sub object_LinkExecute(cmdstr As String, cancel As Integer)

The LinkExecute event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

cmdstr	The command string expression sent by the destination application.

cancel	An integer that tells the destination whether the command string was accepted or refused.  Setting cancel to 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.)

Remarks

There is no required syntax for cmdstr.  How your application responds to different strings is completely up to you.

If you haven't created a LinkExecute event procedure, Visual Basic rejects command strings from destination applications.


See Also

LinkClose Event

LinkError Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property


LinkExecute Event Applies To

Form Object

MDIForm Object


LinkNotify Event

See Also	Example	Applies To

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

Private Sub object_LinkNotify([index As Integer])

The LinkNotify event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

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

LinkClose Event

LinkError Event

LinkExecute Method

LinkMode Property

LinkOpen Event

LinkRequest Method

LinkTopic Property


LinkNotify Event Applies To

Label Control

PictureBox Control

TextBox Control


LinkOpen Event

See Also	Applies To

Occurs when a DDE conversation is being initiated.

Syntax

Private Sub Form_LinkOpen(cancel As Integer)

Private Sub MDIForm_LinkOpen(cancel As Integer)

Private Sub object_LinkOpen([index As Integer,]cancel As Integer)

The LinkOpen event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

cancel	An integer that determines whether the DDE conversation is established or not.  Leaving cancel set to 0 (the default) establishes the conversation.  Setting cancel to any nonzero value refuses the conversation.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

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

LinkClose Event

LinkError Event

LinkExecute Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkTopic Property


LinkOpen Event Applies To

Form Object

Label Control

MDIForm Object

PictureBox Control

TextBox Control


Load Event

See Also	Example	Applies To

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

Private Sub Form_Load( )

Private Sub MDIForm_Load( )

Remarks

Typically, you use a Load event procedure to include initialization code for a form [image] for example, code that specifies default settings for controls, indicates contents to be loaded into ComboBox or ListBox controls, and initializes form-level variables.

The Load event occurs after the Initialize event.

When you reference a property of an unloaded form in code, the form is automatically loaded but isn't automatically made visible unless the MDIChild property is set to True.  If an MDIForm object isn't loaded and an MDI child form is loaded, both the MDIForm and the child form are automatically loaded and both become visible.  Other forms aren't shown until you either use the Show method or set the Visible property to True.

The following code in an MDIForm 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.

Because all child forms become visible when loaded, the reference to the Caption property 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

Activate, Deactivate Events

Load Statement

QueryUnload Event

Unload Event

Unload Statement


Load Event Applies To

Form Object

MDIForm Object


LostFocus Event

See Also	Example	Applies To

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

Private Sub Form_LostFocus( )

Private Sub object_LostFocus([index As Integer])

The LostFocus event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

A LostFocus event procedure is primarily useful for verification and validation updates.  Using LostFocus can cause validation to take place as the user moves the focus from the control.  Another use for this type of event procedure is enabling, disabling, hiding, and displaying other objects as in a GotFocus event procedure.  You can also reverse or change conditions that you set up in the object's GotFocus event procedure.


See Also

ActiveControl Property

ActiveForm Property

GotFocus Event

SetFocus Method

TabIndex Property

TabStop Property


LostFocus Event Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

OptionButton Control

PictureBox Control

TextBox Control


MouseDown, MouseUp Events

See Also	Example	Applies To

Occur when the user presses (MouseDown) or releases (MouseUp) a mouse button.

Syntax

Private Sub Form_MouseDown(button As Integer, shift As Integer, x As Single, y As Single)

Private Sub MDIForm_MouseDown(button As Integer, shift As Integer, x As Single, y As Single)

Private Sub object_MouseDown([index As Integer,]button As Integer, shift As Integer, x As Single, y As Single)

Private Sub Form_MouseUp(button As Integer, shift As Integer, x As Single, y As Single)

Private Sub MDIForm_MouseUp(button As Integer, shift As Integer, x As Single, y As Single)

Private Sub object _MouseUp([index As Integer,]button As Integer, shift As Integer, x As Single, y As Single)

The MouseDown and MouseUp event syntaxes have these parts:

Part	Description

object	Returns an object expression that evaluates to an object in the Applies To list.

index	Returns an integer that uniquely identifies a control if it's in a control array.

button	Returns an integer that identifies the button that 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).  These bits correspond to the values 1, 2, and 4, respectively.  Only one of the bits is set, indicating the button that caused the event.

shift	Returns an integer that corresponds to the state of the SHIFT, CTRL, and ALT keys when the button specified in the button argument is 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.  The shift argument 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 are pressed.  For example, if both CTRL and ALT were pressed, the value of shift would be 6.

x, y	Returns a number that specifies the current location of the mouse pointer.  The x and y values are always expressed in terms of the coordinate system set by the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties of the object.

Remarks

Use a MouseDown or MouseUp event procedure to specify actions that will occur when a given mouse button is pressed or released.  Unlike the Click and DblClick events, MouseDown and MouseUp events enable 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 returned by a mouse event may not always be in the internal 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 use constants listed in the Visual Basic (VB) object library in the Object Browser to define the bits within the argument:

Constant (Button)	Value	Description

vbLeftButton	1	Left button is pressed.

vbRightButton	2	Right button is pressed.

vbMiddleButton	4	Middle button is pressed.

Constant (Shift)	Value	Description

vbShiftMask	1	SHIFT key is pressed.

vbCtrlMask	2	CTRL key is pressed.

vbAltMask	4	ALT key is pressed.

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 event 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 and MouseUp, the button argument indicates exactly one button per event; for MouseMove, it indicates the current state of all buttons.


See Also

Click Event

DblClick Event

MouseMove Event

MousePointer Property


MouseDown, MouseUp Events Apply To

CheckBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Image Control

Label Control

ListBox Control

MDIForm Object

OptionButton Control

PictureBox Control

TextBox Control


MouseMove Event

See Also	Example	Applies To

Occurs when the user moves the mouse.

Syntax

Private Sub Form_MouseMove(button As Integer, shift As Integer, x As Single, y As Single)

Private Sub MDIForm_MouseMove(button As Integer, shift As Integer, x As Single, y As Single)

Private Sub object_MouseMove([index As Integer,] button As Integer, shift As Integer, x As Single, y As Single)

The MouseMove event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

button	An integer that corresponds to 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).  These bits correspond to the 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 are pressed.

shift	An integer that corresponds to the state of the SHIFT, CTRL, and ALT keys.  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.  The shift argument 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 are pressed.  For example, if both CTRL and ALT were pressed, the value of shift would be 6.

x, y	A number that specifies the current location of the mouse pointer.  The x and y values are always expressed in terms of the coordinate system set by the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties of the object.

Remarks

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 use constants listed in the Visual Basic (VB) object library in the Object Browser to define the bits within the argument:

Constant (Button)	Value	Description

vbLeftButton	1	Left button is pressed.

vbRightButton	2	Right button is pressed.

vbMiddleButton	4	Middle button is pressed.

Constant (Shift)	Value	Description

vbShiftMask	1	SHIFT key is pressed.

vbCtrlMask	2	CTRL key is pressed.

vbAltMask	4	ALT key is pressed.

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.

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, as in this example:

LeftDown = (Button And vbLeftButton) > 0
CtrlDown = (Shift And vbCtrlMask) > 0

Then, in a procedure, you can test for any combination of conditions, as in this 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 buttons are pressed.  For MouseDown and MouseUp, the button argument indicates exactly one button per event.

Any time you move a window inside a MouseMove event, it can cause a cascading event.  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

Click Event

DblClick Event

MouseDown, MouseUp Events

MousePointer Property


MouseMove Event Applies To

CheckBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Image Control

Label Control

ListBox Control

MDIForm Object

OptionButton Control

PictureBox Control

TextBox Control


Paint Event

See Also	Example	Applies To

Occurs when part or all of a form or PictureBox control is exposed after it has been moved or enlarged or after a window that was covering the object has been moved.

Syntax

Private Sub Form_Paint( )

Private Sub object_Paint([index As Integer])

The Paint event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

A Paint event 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.

The Paint event is invoked when the Refresh method is used.  If the AutoRedraw property is set to True, repainting or redrawing is automatic, so no Paint events are necessary.

If the ClipControls property is set to 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 event procedure for the following:

Moving or sizing a form or control.

Changing any variables that affect size or 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

AutoRedraw Property

Circle Method

ClipControls Property

Line Method

Print Method

PSet Method

Refresh Method

Resize Event


Paint Event Applies To

Form Object

PictureBox Control


PathChange Event

See Also	Example	Applies To

Occurs when the path is changed by setting the FileName or Path property in code.

Syntax

Private Sub object_PathChange([index As Integer])

The PathChange event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

You can use a PathChange event procedure to respond to path changes in a FileListBox control.  When you assign a string containing a new path to the FileName property, the FileListBox control invokes the PathChange event.


See Also

FileName Property

Path Property

Pattern Property

PatternChange Event


PathChange Event Applies To

FileListBox Control


PatternChange Event

See Also	Example	Applies To

Occurs when the file listing pattern, such as "*.*", is changed by setting the FileName or Pattern property in code.

Syntax

Private Sub object_PatternChange([index As Integer])

The PatternChange event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

You can use a PatternChange event procedure to respond to pattern changes in a FileListBox control.  When you assign a string containing a new pattern to the FileName property, the FileListBox invokes the PathChange event.


See Also

FileName Property

Path Property

PathChange Event

Pattern Property


PatternChange Event Applies To

FileListBox Control


QueryUnload Event

See Also	Example	Applies To

Occurs before a form or application closes.  When an MDIForm object closes, the QueryUnload event occurs first for the MDI form and then in all MDI child forms.  If no form cancels the QueryUnload event, the Unload event occurs first in all other forms and then in an MDI form.  When a child form or a Form object closes, the QueryUnload event in that form occurs before the form's Unload event.

Syntax

Private Sub Form_QueryUnload(cancel As Integer, unloadmode As Integer)

Private Sub MDIForm_QueryUnload(cancel As Integer, unloadmode As Integer)

The QueryUnload event syntax has these parts:

Part	Description

cancel	An integer.  Setting this argument to any value other than 0 stops the QueryUnload event in all loaded forms and stops the form and application from closing.

unloadmode	A value or constant indicating the cause of the QueryUnload event, as described in Return Values.

Return Values

The unloadmode argument returns the following values:

Constant	Value	Description

vbFormControlMenu	0	The user chose the Close command from the Control menu on the form.

vbFormCode	1	The Unload statement is invoked from code.

vbAppWindows	2	The current Microsoft Windows operating environment session is ending.

vbAppTaskManager	3	The Microsoft Windows Task Manager is closing the application.

vbFormMDIForm	4	An MDI child form is closing because the MDI form is closing.

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Remarks

This event is typically used to make sure there are no unfinished tasks in the forms included in an application before that application closes.  For example, if a user has not yet saved some new data in any form, your application can prompt the user to save the data.

When an application closes, you can use either the QueryUnload or Unload event procedure to set the Cancel property 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

Unload Event

Unload Statement


QueryUnload Event Applies To

Form Object

MDIForm Object


Resize Event

See Also	Example	Applies To

Occurs when a form is first displayed or the size of an object changes.

Syntax

Private Sub Form_Resize( )

Private Sub object_Resize(height As Single, width As Single)

The Resize event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

height	Number specifying the new height of the control.

width	Number specifying the new width of the control.

Remarks

Use a Resize event procedure to move or resize controls when the parent form is resized.  You can also use this event procedure to recalculate variables or properties, such as ScaleHeight and ScaleWidth, that may depend on the size of the form.  If you want graphics to maintain sizes proportional to the form when it's resized, invoke the Paint event by using the Refresh method in a Resize event procedure.

Whenever the AutoRedraw property is set to False and the form is resized, Visual Basic also calls the related events, Resize and Paint, in that order.  When you attach procedures for these related events, be sure their actions don't conflict.

When an OLE container control's SizeMode property is set to 2 (Autosize), the control is automatically sized according to the display size of the object contained 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 for the object before the OLE container control is resized.  The height and width 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 height and width parts in the Resize event.


See Also

AutoRedraw Property

Load Statement

Paint Event

Refresh Method

Show Method


Resize Event Applies To

Form Object

MDIForm Object

PictureBox Control


RowColChange Event

See Also	Example	Applies To

Occurs when the current cell changes to a different cell.

Syntax

Private Sub object_RowColChange ([index As Integer, lastrow As String, lastcol As Integer])

The RowColChange event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it is in a control array.

lastrow	(For DBGrid control) A string expression specifying the previous row position.

lastcol	(For DBGrid control) An integer specifying the previous column position.

Remarks

This event occurs whenever the user clicks a cell other than the current cell or when you programmatically change the current cell within a selection using the Col and Row properties.

The SelChange event also occurs when a user clicks a new cell, but doesn't occur when you programmatically change the selected range without changing the current cell.

For the DBGrid control, the position of the current cell is provided by the Bookmark and ColIndex properties.  The previous cell position is specified by lastrow and lastcol.  If you edit data and then move the current cell position to a new row, the update events for the original row are completed before another cell becomes the current cell.


RowColChange Event Applies To

DBGrid Control

Grid Control


See Also

Col, Row Properties

SelChange Event


Scroll Event

See Also	Example	Applies To

Occurs when a user repositions the scroll box on a scroll bar or scrolls a DBGrid control horizontally or vertically.

Syntax

Private Sub dbgrid_Scroll([cancel As Integer])

Private Sub object_Scroll( )

The Scroll event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

cancel	Determines whether the scroll operation succeeds and the DBGrid is repainted, as described in Remarks.

Remarks

For a DBGrid control, this event occurs when the user scrolls the grid horizontally or vertically but before the grid is repainted to display the results of the scroll operation.

Setting cancel to True causes the DBGrid scroll operation to fail, and no repaint operation occurs.  If the Refresh method is invoked within this event, the grid is repainted in its new (scrolled) arrangement even if cancel is set to True.  However, in this case, the grid is repainted again because the scroll operation fails and it snaps back to its previous position.

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

Change Event


Scroll Event Applies To

DBGrid Control

HScrollBar, VScrollBar Controls


SelChange Event

See Also	Example	Applies To

Occurs when the current range changes to a different cell or range of cells.

Syntax

Private Sub DBGrid_SelChange ([cancel As Integer])

Private Sub object_SelChange( )

The SelChange event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

cancel	Determines whether the selection reverts to its position before the event occurred.

Remarks

The SelChange event occurs whenever a user clicks a cell other than the current 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 for a Grid control by changing the selected region using the SelEndCol, SelStartCol, SelEndRow, and SelStartRow properties.  For a DBGrid control, change the selected region using the SelStartCol, SelEndCol, and SelectedRows( ) properties.

The RowColChange event also occurs when a user clicks a new cell but doesn't occur while a user drags the selection across the Grid control or when you programmatically change the selection without moving the current cell.

For the DBGrid control, setting cancel to True causes the selection to revert to the cell or range active before the event occurred.


SelChange Event Applies To

DBGrid Control

Grid Control


See Also

RowColChange Event

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties


Timer Event

See Also	Example	Applies To

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

Private Sub object_Timer([index As Integer])

The Timer event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that uniquely identifies a control if it's in a control array.

Remarks

Use this event procedure to tell Visual Basic what to do after each Timer control interval has elapsed.  When you're 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 property is greater than 0, the Timer event waits for the period specified in the Interval property.


See Also

Enabled Property

Interval Property

Timer Function


Timer Event Applies To

Timer Control


Unload Event

See Also	Example	Applies To

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 a user closing the form using the Close command on the Control menu or an Unload statement.

Syntax

Private Sub object_Unload(cancel As Integer)

The Unload event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

cancel	Integer that determines whether the form is removed from the screen.  If cancel is 0, the form is removed.  Setting cancel to any nonzero value prevents the form from being removed.

Remarks

Setting cancel to any nonzero value prevents the form from being removed, but doesn't stop other events, such as exiting from the Microsoft Windows operating environment.  Use the QueryUnload event to stop exiting from Windows.

Use an Unload event procedure to verify that the form should be unloaded or to specify actions that you want to take place when the form is unloaded.  You can also include any form-level validation code you may need for closing the form or saving the data in it to a file.

The QueryUnload event occurs before the Unload event. The Unload event occurs before the Terminate event.

The Unload event can be caused by using the Unload statement, or by the user choosing the Close command on a form's Control menu, exiting the application with the End Task button on the Windows Task List, closing the MDI form for which the current form is a child form, or exiting the Microsoft Windows operating environment while the application is running.


See Also

Load Event

Load Statement

QueryUnload Event

Unload Statement


Unload Event Applies To

Form Object

MDIForm Object


Activate, Deactivate Events Example

This example updates the status bar text to display the caption of the active form.  To try this example, create a Form object (Form1) and a new MDIForm object (MDIForm1).  On MDIForm1, draw a PictureBox control containing a Label control.  On Form1, set the MDIChild property to True.  Paste the MDIForm_Load event procedure code into the Declarations section of the MDIForm object.  Paste the Form_Activate event procedure code into the Declarations section of the MDI child form, and then press F5.

Private 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

Private Sub Form_Activate ()

' Set status bar text.

MDIForm1.Label1.Caption = "Current form: " & Me.Caption

End Sub


Change Event Example

This example displays the numeric setting of a horizontal scroll bar's Value property in a TextBox control.  To try this example, create a form with a TextBox control and an HScrollBar control (set Min to 0, Max to 1000, LargeChange to 100, and SmallChange to 1), and then paste the code into the Declarations section of a form that contains a horizontal scroll bar (HScrollBar control) and a TextBox control.  Press F5 and click the horizontal scroll bar.

Private 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

Private Sub HScroll1_Change ()

Text1.Text = HScroll1.Value

End Sub


Click Event Example

In this example, each time a PictureBox control 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 PictureBox control positioned at the lower-left corner of the form, and then press F5 and click the PictureBox.

Private Sub Picture1_Click ()

Picture1.Move Picture1.Left + 750, Picture1.Top - 550

End Sub


DragDrop Event Example

This example demonstrates the visual effect of dropping a PictureBox control onto another PictureBox control.  To try this example, paste the code into the Declarations section of a form that contains three PictureBox controls.  Set the DragMode property for Picture1 and Picture2 to 1 (Automatic).  Use the Picture property to assign bitmaps to Picture1 and Picture2, and then press F5 and drag Picture1 or Picture2 over Picture3.

Private 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 Example

This example demonstrates one way to indicate a valid drop target.  The pointer changes from the default arrow to a special icon when a TextBox control is dragged over a PictureBox control.  The 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 TextBox and a PictureBox.  Set the TextBox control's DragMode property to 1, and then press F5 and drag the TextBox over the PictureBox.

Private 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

Private Sub Picture1_DragDrop (Source As Control, X As Single, Y As Single)

Source.DragIcon = LoadPicture()	' Unload icon.

End Sub


DropDown Event Example

This example updates a ComboBox control 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 ComboBox control and two OptionButton controls.  Set the Name property of both OptionButton controls to OptionGroup, and then press F5 and click the OptionButton controls.  The ComboBox control reflects different carriers depending on the OptionButton selected.

Private Sub Form_Load ()

Combo1.Text = ""	' Clear combo box.

End Sub

Private 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 Example

This example displays a status bar message when a button in an OptionButton group gets the focus.  To try this example, paste the code into the Declarations section of a form that contains two OptionButton controls and a Label control.  Set the Name property for both OptionButton controls to OptionGroup, and then press F5 and click the OptionButton controls.

Private Sub Form_Load ()

Label1.AutoSize = True

End Sub

Private 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

Private Sub OptionGroup_LostFocus (Index As Integer)

Label1.Caption = ""

End Sub


KeyDown, KeyUp Events Example

This example demonstrates a generic keyboard handler that responds to the F2 key and to all the associated ALT, SHIFT, and CTRL key combinations.  The key constants are listed in the Visual Basic (VB) object library in the Object Browser.  To try this example, paste the code into the Declarations section of a form that contains a TextBox control, and then press F5 and press F2 with various combinations of the ALT, SHIFT, and CTRL keys.

Private Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer)

Dim ShiftDown, AltDown, CtrlDown, Txt

Const vbKeyF2 = &H71	' Define constants.

Const vbShiftMask = 1

Const vbCtrlMask = 2

Const vbAltMask = 4

ShiftDown = (Shift And vbShiftMask) > 0

AltDown = (Shift And vbAltMask) > 0

CtrlDown = (Shift And vbCtrlMask) > 0

If KeyCode = vbKeyF2 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 = "CTRL+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 Example

This example converts text entered into a TextBox control to uppercase.  To try this example, paste the code into the Declarations section of a form that contains a TextBox, and then press F5 and enter something into the TextBox.

Private Sub Text1_KeyPress (KeyAscii As Integer)

Char = Chr(KeyAscii)

KeyAscii = Asc(UCase(Char))

End Sub


LinkError Event Example

This example is attached to a TextBox control, MyTextBox, that 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.  You can adapt this code to a source form by substituting Form_LinkError for MyTextBox_LinkError.  This example is for illustration only.

Private 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 Example

This 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.

Private 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 Example

This example is attached to a PictureBox control, Picture1, that has its LinkMode property set to 3 (Notify) and its LinkTopic and LinkItem properties set to specify a graphic in the source.  When the source changes this data, the procedure updates the PictureBox control immediately only if the PictureBox is on the active form; otherwise, it sets a flag variable.  This example is for illustration only.

Private 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


Load Event Example

This example loads items into a ComboBox control when a form is loaded.  To try this example, paste the code into the Declarations section of a form that contains a ComboBox, and then press F5.

Private 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


LostFocus Event Example

This example changes the color of a TextBox control when it receives or loses the focus (selected with the mouse or TAB key) and displays the appropriate text in the Label control.  To try this example, paste the code into the Declarations section of a form that contains two TextBox controls and a Label control, and then press F5 and move the focus between Text1 and Text2.

Private Sub Text1_GotFocus ()

' Show focus with red.

Text1.BackColor = RGB(255, 0, 0)

Label1.Caption = "Text1 has the focus."

End Sub

Private Sub Text1_LostFocus ()

' Show loss of focus with blue.

Text1.BackColor = RGB(0, 0, 255)

Label1.Caption = "Text1 doesn't have the focus."

End Sub


MouseDown, MouseUp Events Example

This example demonstrates a simple paint application.  The MouseDown event procedure works with a related MouseMove event procedure to enable painting when any mouse button is pressed and dragged.  The MouseUp event procedure disables painting.  To try this example, paste the code into the Declarations section of a form; and then press F5, click the form, and move the mouse while the mouse button is pressed.

Dim PaintNow As Integer

Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As

Single, Y As Single)

PaintNow = True	' Enable painting.

End Sub

Private Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = False	' Disable painting.

End Sub

Private 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

Private Sub Form_Load ()

DrawWidth = 10	' Use wider brush.

ForeColor = RGB(0, 0, 255)	' Set drawing color.

End Sub


MouseMove Event Example

This example demonstrates a simple paint application.  The MouseDown event procedure works with a related MouseMove event procedure to enable painting when any mouse button is pressed.  The MouseUp event procedure disables painting.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form and move the mouse while the mouse button is pressed.

Dim PaintNow As Integer	' Declare variable.

Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = True	' Brush on.

End Sub

Private Sub Form_MouseUp (Button As Integer, X As Single, Y As Single)

PaintNow = False	' Turn off painting.

End Sub

Private 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

Private Sub Form_Load ()

DrawWidth = 10	' Use wider brush.

ForeColor = RGB(0, 0, 255)	' Set drawing color.

End Sub


Paint Event Example

This example draws a diamond that intersects the midpoint 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, and then press F5 and resize the form.

Private Sub Form_Paint ()

Dim HalfX, HalfY	' Declare variables.

HalfX = ScaleLeft + ScaleWidth / 2	' Set to one-half of width.

HalfY = ScaleTop + ScaleHeight / 2	' Set to one-half of height.

' Draw a diamond.

Line (ScaleLeft, HalfY) - (HalfX, ScaleTop)

Line -(ScaleWidth + ScaleLeft, HalfY)

Line -(HalfX, ScaleHeight + ScaleTop)

Line -(ScaleLeft, HalfY)

End Sub

Private Sub Form_Resize

Refresh

End Sub


PathChange Event Example

This example demonstrates how to update a Label control to reflect the current path for a FileListBox control.  Double-clicking a directory name displays a list of that directory's files in the FileListBox; 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 control, a DirListBox control, and a FileListBox control, and then press F5.

Private Sub File1_PathChange ()

Label1.Caption = "Path: " & Dir1.Path	' Show path in Label.

End Sub

Priavte Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set file path.

End Sub

Private Sub Form_Load ()

Label1.Caption = "Path: " & Dir1.Path	' Show path in Label.

End Sub


PatternChange Event Example

This example updates a FileListBox control with files matching the pattern entered in a TextBox control.  If a full path is entered into the TextBox, 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 TextBox control, a Label control, a FileListBox control, and a CommandButton control, and then press F5 and enter a valid file pattern in the TextBox.

Private Sub Form_Load ()

Command1.Default = True	' Set Default property.

Command1.Caption = "OK"	' Set Caption.

End Sub

Private 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

Private Sub File1_PatternChange ()

Text1.Text = File1.Pattern	' Set text to new pattern.

End Sub


QueryUnload Event Example

This example uses an MDIForm object containing two MDI child forms.  When you choose the Close command from the Control menu to close a form, a different message is displayed than if you choose the Exit command from the File menu.  To try this example, create an MDIForm, and then use the Menu Editor 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 then press F5 to run the program.

' Paste into Declarations section of MDIForm1.

Private Sub MDIForm_Load ()

Dim NewForm As New Form1	' New instance of Form1.

NewForm.Caption = "Form2"	' Set caption and show.

End Sub

Private Sub FileExit_Click ()

Unload MDIForm1	' Exit the application.

End Sub

Private 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.

Private 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


Resize Event Example

This example automatically resizes a TextBox control 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 TextBox.  Set the TextBox control's MultiLine property to True, its ScrollBars property to 3, and its BorderStyle property to 0, and then press F5 and resize the form.

Private Sub Form_Load ()

Text1.Text = ""	' Clear text.

End Sub

Private Sub Form_Resize ()

Text1.Move 0,0, ScaleWidth, ScaleHeight

End Sub


RowColChange, SelChange Events Example; Cols, Rows Properties Example

This example displays the location of the current cell and the range of the selection as a user selects cells or ranges.  When selecting a range, the current cell doesn't change.  Select a range, and then click the form to move the current cell around the perimeter of the selection.  Notice that the selected range doesn't change.

To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control and two Label controls.  Copy the code into the Declarations section, and then press F5 to run the program.

Private Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Private Sub Grid1_RowColChange ()

Msg = "Current Cell: " & Chr(64 + Grid1.Col)

Mst = Msg & Grid1.Row

Label1.Caption = Msg

End Sub

Private 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

Private Sub Form_Click ()

' This procedure moves the current cell around

' the perimeter of the 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


Scroll Event Example

This example changes the size of a Shape control to correspond to the value of a horizontal scroll bar (HScrollBar) as you drag the scroll 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 control, and an HScrollBar control.  Set the Index property for the Shape control to 0 to create a control array.  Then press F5 and move the scroll bar.

Private 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

Private Sub HScroll1_Change ()

Label1.Caption = "Changed"	' Display message after change.

End Sub

Private 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


Timer Event Example

This example demonstrates a digital clock.  To try this example, paste the code into the Declarations section of a form that contains a Label control and a Timer control, and then press F5.

Private Sub Form_Load ()

Timer1.Interval = 1000	' Set Timer interval.

End Sub

Private Sub Timer1_Timer ()

Label1.Caption = Time	' Update time display.

End Sub

This example moves a PictureBox control across a form.  To try this example, paste the code into the Declarations section of a form that contains a Timer control and a PictureBox control, and then press F5.  For a better visual effect you can assign a bitmap to the PictureBox using the Picture property.

Dim DeltaX, DeltaY As Integer	' Declare variables.

Private 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

Private Sub Form_Load ()

Timer1.Interval = 1000	' Set Interval.

DeltaX = 100	' Initialize variables.

DeltaY = 100

End Sub


Unload Event Example

This example demonstrates a simple procedure to close a form while prompting the user with various message boxes.  In an actual application, you can add calls to general purpose Sub procedures that emulate the processing of the Exit, Save, and Save As commands on the File menu in Visual Basic.  To try this example, paste the code into the Declarations section of a form, and then press F5.  Once the form is displayed, press ALT+F4 to close the form.

Private 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	' Don't allow close.

Cancel = -1

Msg = "Command has been canceled."

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


Creating a General Procedure

See Also

A general procedure tells an 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 a form module, standard module, or class module.  General procedures can be either public or private.  Public general procedures can be accessed from any module in your application, provided you qualify the name of the procedure with the name of the module that contains the procedure.  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 module for which you want to write the procedure.

2.	From the Insert menu, choose Procedure.

3.	In the text box, type a name for the procedure.

4.	Under Type, select Sub to create a Sub procedure, Function to create a Function procedure, or Property to create a Property procedure.

Note that a Function procedure returns a value and a Sub procedure doesn't.

5.	Under Scope, select Public to create a procedure you can invoke from outside the module, or Private to create a procedure you can only invoke from within the module.

6.	Choose OK.

Visual Basic sets up a procedure template so you can enter code for the general procedure.

Note   You can also create a new procedure in the current module by typing Sub ProcedureName, Function ProcedureName, or Property 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 = returnvalue
End Function

Use this syntax when writing a Property procedure:

Property {Get|Let|Set} propertyname [(arguments)] [As type]
local variable and constant declarations
statements
End Property

Note   General procedures are Public by default.

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 standard 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 off load code by attaching to the form or its controls short event procedures that call general procedures in the standard module(s).  Place global declarations in any module.

Multiple-form application startup.  Create a standard module and write a general procedure called Main for your startup procedure.  You also need to specify Sub Main in the Startup Form option in the Project tab of the Options dialog box.


See Also

Attaching an Event Procedure to a Form or Control

Creating a Procedure

Entering and Editing Code

Insert Procedure Dialog Box


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 of the Add Watch and Edit Watch dialog boxes 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 select the Break When Value 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 isn't suspended until the expression MyVar > 5 evaluates to true.  Note that a simple string variable can't 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 watch expression 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 a Procedure context.  Expressions whose components are defined at the module level can have Procedure or Module context, and globally scoped expressions can have any context.


See Also

Add Watch Dialog Box

Adding Watch Expressions

Debug Window

Deleting Watch Expressions

Edit Watch Dialog Box

Editing Watch Expressions


Using the Immediate Window

See Also

To execute code in the Immediate window while in break mode

1.	Type a line of code in the Immediate window.

2.	Press ENTER to execute the statement.

Use the Immediate 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.

Call procedures as you would in code.

View debugging output while the program is running.

Note   Immediate window statements are executed in a context [image] that is, as if they are entered in a specific module.  This context appears in the title bar of the Debug window.

If you need help on syntax for functions, statements, properties, or methods while working in the Immediate window, select the keyword or the property or method name, and press F1.


See Also

Debug Window

Debugging Checklist


Displaying or Hiding the Grid

See Also

At design time, the interface of a Form 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 Tools menu, choose Options.

2.	Select the Environment tab.

3.	Click the Show Grid check box to toggle the display of the grid on or off.

4.	Choose OK.


See Also

Aligning an Item to the Grid

Changing Grid Spacing

Environment Options Tab


Changing Grid Spacing

See Also

You can adjust the spacing of the grid points displayed on the active Form.  You specify grid spacing in pixels.

To change grid spacing

1.	From the Tools menu, choose Options.

2.	Select the Environment tab.

3.	In the Width box, type the width you want between horizontal points.

4.	In the Height box, type the width you want between vertical points.

5.	Choose OK.


See Also

Aligning an Item to the Grid

Displaying or Hiding the Grid

Environment Options Tab


Displaying Graphics on a Form

See Also

You can add graphics to Form objects 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 PictureBox or Image control as the display area for a bitmap, icon, or metafile, or as a background graphic, using the entire Form 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 PictureBox or Image control on the Form.

2.	In the Properties window, select the Picture property.

3.	In the right column, Visual Basic displays the current type of image.  Click the Properties button at the right of the Settings box.

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 control that serves as the container for the graphic.  If necessary, resize the container.

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 the Picture property.

3.	Follow steps 3-5 as listed above.

Visual Basic displays the graphic on the Form.  If necessary, resize the Form to properly display the graphic.

To add a graphic at design time by copying and pasting

1.	Open the other application and copy the graphic onto the Clipboard.

2.	Switch to Visual Basic.

3.	Select the Form or control into 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 Form objects can be memory-intensive.  To save memory, use a PictureBox or Image control to display a foreground graphic.

When using a PictureBox control, set the AutoSize property to True to automatically resize the control to fit the picture.  When AutoSize property 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

AutoSize Property

Drawing Lines and Shapes on a Form

Form Object

Form Window

Image Control

PictureBox Control

Properties Window

Setting Form and Control Properties


Drawing Lines and Shapes on a Form

See Also

You can use the Line control to draw simple lines on Form objects, and the Shape control to draw rectangles (regular or rounded corners), squares (regular or rounded corners), ovals, and circles on Form objects.

To draw a line on 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.

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.

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

BackColor, ForeColor Properties

BorderStyle Property

Circle Method

Displaying Graphics on a Form

Form Window

Line Control

Line Method

PictureBox Control

Setting Form and Control Properties

Shape Control

Shape Property

Toolbox


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 a Toolbox button.

2.	Click the Form on which 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 Toolbox button you want.

The control appears in the center of the Form.  Move and resize it as needed for your application.

Note   OptionButton controls 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 OptionButton controls inside a Frame or PictureBox control.


See Also

Attaching an Event Procedure to a Form or Control

Creating a Control Array

Frame Control

OptionButton Control

PictureBox Control

Setting Form and Control Properties

Toolbox


Selecting Controls

See Also

To select a control

On a Form, click the control you want.

To select multiple controls

1.	Click one of the controls you want to select on the Form.

2.	With the control selected, press and hold down the CTRL key, and then click each additional control you want to select.  You can cancel the selection of a control in a selection by holding down the CTRL key and clicking the control.

Or

On the Form, click and drag a box around the controls you want to select.

Note   To select multiple controls within a container (Frame or PictureBox controls), first cancel the selection of 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

Form Object

Form Window

Frame Control

PictureBox Control

Properties Window


Aligning an Item to the Grid

See Also

You can automatically or manually align items to the grid as you draw them on a Form.  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 Tools menu, choose Options.

2.	Select the Environment tab.

3.	Under Form Design Grid, select Align Controls to Grid.

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.

Or

Click the right mouse button and choose Align to Grid from the context menu.


See Also

Changing Grid Spacing

Displaying or Hiding the Grid

Environment Options Tab


Creating a Menu Bar

See Also

You can use the Menu Editor 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.	Open the Form for which you want to create a menu bar.

2.	From the Tools menu, choose Menu Editor (CTRL+E), or use the toolbar shortcut:

Or

Select the Form object, click the right mouse button, and then choose Menu Editor from the context menu.

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 menu control array.

To assign a shortcut key to a menu item, select a key from the Shortcut drop-down list.

Enter a unique number in the HelpContextID text box if you plan to provide a context-sensitive Help topic for the current control.

Select a value from the NegotiatePosition drop-down list to choose how the menu bar negotiates menu items from active applications that you include in your application through OLE.  NegotiatePosition is only valid for menu titles (such as File, Edit, or Help).

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.

Select the WindowList box if you want the current menu control to include the name of open MDI child forms.


See Also

Attaching an Event Procedure to a Form or Control

Creating a Menu Control Array

Menu Control

Menu Editor

Specifying Access Keys


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.	Select the Form.

2.	From the Tools menu, choose Menu Editor.

Or

Click the Menu Editor button on the toolbar:

Or

Click the right mouse button and choose Menu Editor from the context menu.

3.	In the Caption text box, type the text for the first menu title that you want to appear on the menu bar.

The menu title text is displayed in the menu control list box.

4.	In the Name text box, type the name that you will use to refer to the menu control in code.  Leave the Index property empty.

5.	At the next indentation level, create the menu item that will become the first element in the array by setting its Caption and Name properties.

6.	Set the Index property for the first element in the array to 0.

7.	Create a second menu item at the same level of indentation as the first.

8.	Set the Name property of the second element to the same as the first element and set its Index property to 1.

9.	Repeat steps 5 [image] 8 for subsequent elements of the array.

Important   Elements of a menu control array must be contiguous in the menu control list box and must be at the same level of indentation.  When you're creating menu control arrays, be sure to include any separator bars that appear on the menu.

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

Adding and Deleting Controls at Run Time

Attaching an Event Procedure to a Form or Control

Index Property

Name Property


Adding and Deleting Menu Commands at Run Time

See Also

After using the Menu Editor 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, and write code within that procedure to load or unload the items at run time.

Note	At run time, you can't remove commands created at design time.


See Also

Adding and Deleting Controls at Run Time

Load Statement

Menu Editor

Unload Statement


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 or not it is enabled.  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 View menu, choose Properties (F4).

Or

Use the toolbar shortcut:

Or

Click the right mouse button, and choose Properties from the context menu.

3.	From the Properties window, select the property you want either by clicking the property name in the Properties 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 an ellipsis.  Click this button to display a dialog box in which you select the settings for the property.

5.	Repeat steps 3 and 4 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

Properties Window


Setting Colors

See Also

You can set background and foreground colors for Form objects and controls using the Color palette.

To set colors with the Color palette

1.	From the View 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, and then select a color on the color box; to change the background color for the selected object, click the outer box, and then select 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 Properties 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.

2.	Click the Properties button 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, Visual Basic substitutes the color-scheme choices the user has made in the Control Panel settings.


See Also

BackColor Property

Color Palette

Creating Custom Colors

ForeColor Property

Properties Window

QBColor Function

RGB Function


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 View 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 Properties window.


See Also

Color Palette

Setting Colors


Attaching an Event Procedure to a Form or Control

See Also

The code you attach to a Form object or control is called an event procedure.  Every Form object 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:

Private Sub ObjectName_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 Private 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.


See Also

Code Window

Creating a Procedure

Entering and Editing Code

Entering Declarations in Code

Option Private Statement

Private Statement

Sub Statement


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 form, standard, or class modules.  To enter module-level declarations, go to the Declarations section of a module.  To enter global declarations, go to the Declarations section of a module and use the Public statement for constants and variables.  You can also use the Dim, Static, and Private keywords to make declarations.

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.

To open the Declarations section of a module

1.	In the Project window, select the form, standard, or class module you want to open and click the View Code button.

Or

Click the right mouse button, and choose View Code from the context menu.

2.	In the Object box, select (General).

The Procedure box automatically displays (Declarations).

3.	Enter the declarations you want.


See Also

Code Window

Declare Statement

Dim Statement

Entering and Editing Code

Private Statement

Project Window

Public Statement

Static Statement


Finding a Procedure

See Also

To find a procedure in a Code window

To view an existing general procedure, select "(general)" from the Object box in the Code window, and then select the procedure in the Procedure box.

Or

To view an event procedure, select the appropriate object from the Object box in the Code window, and then select the event in the Procedure box.

Note   To visually separate procedures in the Code window, you can select the Procedure Separator check box in the Editor tab of the Options dialog box.

To find a procedure in another module

1.	From the View menu, choose Object Browser, or press F2.

2.	Select the project from the Libraries/Projects box.

3.	Select the module from the Classes/Modules list, and the procedure from the Methods/Properties list.

4.	Choose Show.

The procedure you have chosen is displayed in the Code window.

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 the Object Browser.


See Also

Code Window

Code Window Keyboard Shortcuts

Editor Options Tab

Object Browser

Replacing Text in Code

Searching for Text in Code


Saving Your Work

See Also

In Visual Basic, you can save entire projects as well as specific form, standard, and class modules.  You can't, however, save the resource file that is associated with a project in Visual Basic; you must save this with a standard resource editor.

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 filename extension, Visual Basic automatically adds the extension .VBP.

3.	Choose OK.

If you have unsaved form, standard, or class modules in the project, Visual Basic prompts you to save them as well.

To save a new form, standard, or class 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 module you want to save in the Project window.

2.	From the File menu, choose Save File As (CTRL+A).

Or

Click the right mouse button, and choose Save File As from the context menu.

3.	In the File Name text box, type a name for the module.

Unless you type a different filename extension, Visual Basic automatically adds the extension .FRM for form modules, .BAS for standard modules, and .CLS for class modules.

4.	Choose OK.

To save changes to an existing form, standard, or class module

1.	Click the module you want to save.

or

Select the module you want to save in the Project window.

2.	From the File menu, choose Save File (CTRL+S).

Or

Click the right mouse button, and choose Save File from the context menu.


See Also

Code Window

Form Window

Importing a Text File into Code

Project Window

Save File, Save File As Commands (File Menu)

Save Project, Save Project As Commands (File Menu)


Setting Options

See Also

You can use the Options command on the Tools menu to set new preferences or default values for the programming environment or for specific projects.

Use the Environment tab in the Options dialog box to specify attributes of your Visual Basic development environment.

Use the Project tab in the Options dialog box to specify settings for the current Visual Basic project.

Use the Editor tab in the Options dialog box to specify the appearance of your Visual Basic code.  It includes a list of the types of text found in code, and boxes in which you can specify attributes for selected text types.

Use the Advanced tab in the Options dialog box for error handling and compilation options.


See Also

Environment Options Tab

Editor Options Tab

Project Options Tab

Advanced Options Tab


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 (Form objects 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 PictureBox or a custom control that has an Align property.  However, you can place other controls in the PictureBox.  Typically, you use the PictureBox to create a toolbar.  A PictureBox 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 PictureBox must be aligned to the top or bottom of the MDI form internal area.

If you want several MDI child forms in an MDI application to function identically, you can use multiple instances of a single Form, or an array of forms of a single type, instead of designing different child forms.  You can load and create instances of MDI child forms 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).

Select the WindowList check box in the Menu Editor 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.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.


See Also

ActiveForm Property

Align Property

Arrange Method

Dim Statement

Load Statement

Make OLE DLL File Command

MDIChild Property

Me Keyword

Menu Editor

ScaleHeight, ScaleWidth Properties


Using Dynamic Data Exchange (DDE)

See Also

Visual Basic's dynamic data exchange (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 are simplest because they are automatically re-established whenever the application is run.  However, when you create links at design time, the application with which you communicate must contain Copy and Paste Link commands.  Similarly, when you run the Visual Basic project at a later time, the other application must be available or an error occurs.  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 don't need Copy and Paste Link 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.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.


See Also

Creating a DDE Source or Destination Link

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

Make OLE DLL File Command


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 Run menu, choose Set Next Statement (CTRL+F9).

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 Step Into, 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

Code Window

Debugging Checklist

Finding a Procedure

GoTo Statement

Set Next Statement Command (Run Menu)

Step Into, Step Over, Step to Cursor Commands (Run Menu)

Tracing Execution


Specifying a Startup Form

See Also

An application doesn't 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 standard module.

To specify a startup form

1.	From the Tools menu, choose Options.

Visual Basic displays the Options dialog box.

2.	Select the Project tab.

3.	Select a Form from the Startup Form drop-down list box.

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 standard module.

2.	From the Tools menu, choose Options.

Visual Basic displays the Options dialog box.

3.	Select the Project tab.

4.	Select Sub Main from the Startup Form drop-down list box.

5.	Choose OK.

When the project starts execution, Sub Main is called immediately.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.


See Also

Make OLE DLL File Command

Project Options Tab


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 don't assign an icon to a Form, the FORM.ICO file in the \ICONS\MISC subdirectory 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 the Icon property.

3.	Click the Properties button at the right of the Settings box.

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 (located in the \ICONS subdirectory of the main Visual Basic directory).


See Also

Icon Property

Setting Form and Control Properties

Specifying a Startup Form


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 don't 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.

To assign an access key to a menu or command with the Menu Editor

1.	Click the Form with the menu bar.

2.	From the Tools menu, choose Menu Editor (CTRL+E)

Or

Use the toolbar shortcut:

Or

Click the right mouse button, and choose Menu Editor from the context menu.

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

Creating a Menu Bar

Menu Editor

Properties Window


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.

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 the TabStop property.

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.

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

Properties Window

TabIndex Property

TabStop Property


Creating a DDE Source or Destination Link

See Also

You can create data links between a Visual Basic application and other applications that support dynamic data exchange (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 (TextBox, Label, or PictureBox) 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 automatically causes 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 re-established.  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

LinkItem Property

LinkMode Property

LinkRequest Method

LinkTimeout Property

LinkTopic Property


Command Line Switches

See Also

Determines whether Visual Basic compiles and runs a program, compiles and makes an executable (.EXE) file or OLE DLL (.DLL), or sets the argument part of the command line returned by the Command function.

Syntax

vb32[.exe] [[{/run | /r} projectname ] [[{/d compileconst}] {/make | /m } projectname] [{/makedll | /l } projectname] {/cmd argument | /c argument }]

Note	The preceding syntax works for 32-bit versions of Visual Basic.  For 16-bit versions, use vb[.exe] when starting Visual Basic with command line switches.

The parts of the command line switches syntax are:

Part	Description

projectname	The name of your project (.VBP) file.

/run or /r	Tells Visual Basic to compile projectname and run it, using the argument stored in the Command Line Arguments field in the Advanced tab of the Options dialog box.

/make or /m	Tells Visual Basic to compile projectname and make an executable (.EXE) file from it, using the existing settings of the Path, EXEName, and Title properties of the App object.

/makedll or /l	Tells Visual Basic to compile projectname and make an in-process OLE server (.DLL) file from it.

/d or /D	Tells Visual Basic which values to use for conditional compilation constants when making an .EXE with the /make switch or an OLE DLL with the /makedll switch.

compileconst	The names and values of conditional compilation constants used in the project file.

/cmd or /c	Puts argument in the Command Line Arguments field in the Advanced tab of the Options dialog box.  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 box 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.VBP


See Also

App Object

Command Function

Advanced Options Tab


Splitting the Code Window into Panes

See Also

You can split the Code window horizontally into two panes to view different code segments of a 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

Drag the split bar down from the upper-right corner of the Code window, at the top of the vertical scroll bar.

To remove a split from the Code window

Double-click the split bar or drag it to the top or bottom of the Code window.

Note	You can also split the Debug window into panes using the same technique as you use with the Code window.


See Also

Code Window


Stopping Execution

See Also

As you run your application, it may stop executing for one of the following reasons:

An untrapped run-time error occurs.

A trapped run-time error occurs, and Break on All Errors is selected in the Advanced tab in the Options dialog box.

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 in your code (switching the mode to break mode).

Visual Basic encounters an End statement in your code (switching the mode to design time).

You halt execution manually at a given point.

To halt execution manually

To switch to break mode, from the Run menu, choose Break (CTRL+BREAK), or use the toolbar shortcut:

To switch to design time, from the Run menu, choose End, 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 Run menu, choose Restart (SHIFT+F5), Step Into (F8), Step To Cursor (CTRL+F8), or Step Over (SHIFT+F8).


See Also

Adding Watch Expressions

Continuing Execution

Debugging Checklist

End Statement

Ending Execution

Restarting Execution

Starting Execution

Stop Statement


Adding Watch Expressions

See Also

A watch expression is an expression you define to be monitored in the Debug window.  When your application enters break mode, the watch expressions you selected appear in the Watch pane where you can observe their values.

To add a watch expression

1.	From the Tools menu, choose Add Watch.

2.	If an expression is already selected in the Code window, it is automatically displayed in the Expression box.  If no expression is displayed, enter the expression you want to evaluate.  The expression can be a variable, a property, a function call, or any other valid expression.

3.	Select a module or procedure context in the Context group to select the range for which the expression will be evaluated.

Note   Select the narrowest scope that fits your needs.  Selecting all procedures or all modules could slow down module execution considerably, since the expression is evaluated after execution of each statement.  If you select a specific procedure for a context, execution is affected only while the procedure is in the list of active procedure calls.  Click the Calls button to the right of the Procedure box in the Debug window to display the Calls dialog box.

4.	Select an option in the Watch Type group to define how the system responds to the watch expression.  There are three Watch Types:

Type	Description

Watch Expression	The value of the watch expression is displayed.  The current value isn't displayed if the expression context isn't within a procedure listed in the Calls dialog box.

Break When Value Is True	If the expression evaluates to true, execution stops.

Break When Value Changes	If the value of the expression changes, execution stops.

5.	Choose OK.


See Also

Add Watch Dialog Box

Calls Dialog Box

Debug Window

Debugging Checklist

Deleting Watch Expressions

Editing Watch Expressions

Setting and Clearing Breakpoints


Compressing Files with COMPRESS.EXE

See Also

COMPRESS.EXE compresses one or more files.  COMPRESS.EXE is an MS-DOS [image] based utility that is located in the \SETUPKIT subdirectory of the main Visual Basic directory.

Syntax

compress [-r] source destination

compress -r source [destination]

The COMPRESS.EXE syntax has these parts:

Part	Description

-r	Automatically renames compressed files.

source	The source file to be compressed.  You can include multiple files and wildcard characters.

destination	The destination path for the compressed source file.  You can specify a directory.  If source represents multiple files and -r isn't specified, destination must be a directory.  You can't use wildcard characters.


See Also

Compressing the Setup Files


Continuing Execution

See Also

When you run your code, execution may stop if:

An untrapped run-time error occurs.

A trapped run-time error occurs, and Break on All Errors is selected in the Advanced tab of the Options dialog box.

A previously set breakpoint is encountered.

A watch expression, which you set to break when the value has changed or break when the value is true, is encountered.

A Stop statement in your code is encountered (switching the mode to break mode).

An End statement in your code is encountered (switching the mode to design time).

You halt execution manually at a given point.

To halt execution manually

To switch to break mode, from the Run menu, choose Break (CTRL+BREAK), or use the toolbar shortcut:

To switch to design time, from the Run menu, choose End, 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 Run menu, choose Restart (SHIFT+F5), Step Into (F8), Step Over (SHIFT+F8), or Step To Cursor (CTRL+F8).


See Also

Adding a Watch Expression

Debugging Checklist

End Statement

Ending Execution

Restarting Execution

Setting and Clearing Breakpoints

Starting Execution

Stop Statement

Stopping Execution


Creating a Procedure

See Also

Code within a module is organized into procedures.  A procedure tells the application how to perform a specific task.  Use procedures to divide complex code tasks into more manageable units.

To create a procedure

1.	Open the module for which you want to write the procedure.

You can create a Sub, Function, or Property procedure.

2.	Type Sub, Function, or Property.  Press F1 to get Help with syntax.

3.	Type in code for the procedure.

Visual Basic concludes the procedure with the appropriate End Sub, End Function, or End Property statement.

To create a procedure using the Insert Procedure dialog box

1.	Open the module for which you want to write the procedure.

2.	Enter the name for the procedure in the Name box.

3.	Select the type of procedure you want to create: Sub, Function, or Property.

4.	Set the procedure's scope to either Public or Private.

5.	Optionally, you can select the All Local Variables as Statics to add the Static keyword to the procedure definition.

6.	Choose OK to insert the procedure template in the Code window.


See Also

Creating a General Procedure

Entering and Editing Code

Function Statement

Insert Procedure Dialog Box

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Static Statement

Sub Statement


Debugging Checklist

See Also

Debugging is a process by which you find and resolve errors in your code.  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 mistake (that violates the rules of Basic, such as a misspelled word, missing separator, or type mismatch.)

Compile errors include syntax errors, which are errors in grammar or punctuation.  These include mismatched parentheses or an incorrect number of arguments passed to an intrinsic function.

Run-time errors [image] occur after the application starts to execute.  Examples of run-time errors include attempting an illegal operation, such as dividing by zero or writing to a file that doesn't exist.

Logical errors [image] occur when the application doesn't perform as intended and produces incorrect results.

To debug your code

1.	Print the code (some users find it easier to read code on paper than on the screen).

2.	Run the application to find trouble spots:

Run the application until an error stops execution, or stop execution manually at the point where you suspect there is an error (by pressing CTRL+BREAK).

From the Tools menu, choose Options.  Set the appropriate Error Trapping options in the Advanced tab of the Options dialog box.  These options include Break on All Errors, Break in Class Module, and Break on Unhandled Errors.  For automatic checking of syntax, set the Auto Syntax Check option in the Environment tab of the Options dialog box..

Put breakpoints in your error-handling routines and use Resume Next statements.

3.	Use debugging tools and techniques to isolate bugs and monitor code flow:

Set breakpoints to halt execution at certain points to look for incorrect variable types, mix-ups in variable names, flaws in logical comparisons, endless loops, unreadable output, problems with arrays, and so on.  You can also set breakpoints to monitor code flow or examine information in the current state.

Use context-sensitive Help (F1) on variable names to check for conflicts.

Use Step Into (F8), Step Over (SHIFT+F8), or Step To Cursor (CTRL+F8) to trace through your code.

Add a watch expression at design time or use an Instant Watch while in break mode to monitor the value of a particular expression.

Use the Immediate window to test individual lines of code or procedures or to change values while in break mode.

If an error occurs in a loop, define a break expression to determine where the problem occurs.  Use the Immediate window with Set Next Statement to re-execute the loop after making corrections.

Enter break mode and click the Calls button to the right of the Procedure box to see where your code is currently executing and to trace its path.

4.	Try out bug fixes and then make edits:

Test individual lines of new or debugged code in the Immediate window.

When an error is found, use the Replace command on the Edit menu to check other procedures or modules for similar errors.

From the Run menu, choose Restart to reset variables and restart execution from the beginning.


See Also

Adding Watch Expressions

Advanced Options Tab

Calls Dialog Box

Continuing Execution

Deleting Watch Expressions

Editing Watch Expressions

Ending Execution

Entering and Editing Code

Environment Options Tab

Print Command (File Menu)

Replacing Text in Code

Restarting Execution

Resume Statement

Setting and Clearing Breakpoints

Starting Execution

Stopping Execution

Tracing Execution

Using the Immediate Window


Deleting Watch Expressions

See Also

To delete a watch expression in the Watch pane, do any one of the following:

Select the expression and press DEL.

Select the expression and choose Clear from the Edit menu.

Double-click the expression and choose Delete.

Select the expression, choose Edit Watch from the Tools menu, and then choose Delete.

Click the expression with the right mouse button, and then choose Delete from the context menu.


See Also

Debug Window

Debugging Checklist

Edit Watch Dialog Box

Setting and Clearing Breakpoints


Editing Watch Expressions

See Also

To edit a watch expression

1.	Double-click the expression in the Watch pane.

or

Select the expression and choose Edit Watch from the Tools menu.

or

Click the expression with the right mouse button, and choose Edit Watch from the context menu.

2.	Make any changes to the expression, the context, and the watch type.

3.	Choose OK.


See Also

Adding Watch Expressions

Debug Window

Debugging Checklist

Deleting Watch Expressions

Edit Watch Dialog Box

Setting and Clearing Breakpoints


Ending Execution

See Also

To end execution, choose End from the Run menu, or click the End button on the toolbar: .

You can also use the End statement in code.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.


See Also

End Statement

Make OLE DLL File Command

Restarting Execution

Starting Execution

Stopping Execution


Entering and Editing Code

See Also

You enter and edit code in a module.  A module has automatic formatting and syntax checking capabilities built in.

Guidelines

To enter code, insert a form, standard, or class module, or select a module in the Project window and choose View Code, and start typing.

To correct mistakes as you type, press BACKSPACE.

To delete text, select the text 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 you want to indent and press TAB.

To remove an indent, press SHIFT+TAB.

To switch between insert mode and overtype mode, press INSERT.

To add a comment to a line in your code, start the line with an apostrophe (') or use the Rem statement.

To complete a statement, press ENTER at the end of the line or move the insertion point 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 continue a statement on the next line, end the line with a line-continuation character.

To view different portions of your code at the same time, drag the Split bar down from the upper-right corner of the Code window, at the top of the vertical scroll bar.

To define a procedure that accept argument(s), enclose all the argument(s) in parentheses following the name of the procedure.  If there is more than one argument, separate the arguments with a comma.  For example:

Sub IncrementXY(X, Y)

To pass arguments to a procedure, separate them 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 Call keyword is being used before a procedure name.  For example:

Call IncrementXY(X, Y)

To get Help on a keyword, type or select the keyword and press F1.

To make an assignment of one variable to another, use the syntax destination = source.


See Also

Code Window

Code Window Keyboard Shortcuts

Creating a Procedure

Data Type Summary

Entering Declarations in Code

Environment Options Tab

Editor Options Tab

Rem Statement


Importing a Text File into Code

See Also

You can import a text file containing code into the current module and use it in your code.

To import a text file into a module

1.	Open the module into which you want to insert text.

2.	From the Insert menu, choose File.

The Insert File dialog box appears.

3.	Use the Insert File dialog box to select the file to import.

4.	Choose OK.


See Also

Entering and Editing Code

File Command (Insert Menu)

Using Example Code from Online Help


Replacing Text in Code

See Also

To replace text in a module

1.	From the Edit menu, choose Replace.

The Replace dialog box appears.

2.	In the Find What box, type the text you want to search for.

3.	In the Replace With box, type the replacement text.

4.	Select a Search option to specify where to look for the text.

5.	Select a direction from the Direction list box to specify the direction of the search.

6.	To set limits on the search, select:

Find Whole Words Only to search for the complete word by itself, and not as part of another word.

Match Case for an exact match.

Use Pattern Matching to use wildcard characters.

7.	Choose Find Next if you want to confirm the change before replacing the text; choose Replace to replace the highlighted occurrence of the found text and automatically perform a Find Next; or choose Replace All to change all occurrences of the search text automatically.


See Also

Replace Command (Edit Menu)

Searching for Text in Code


Restarting Execution

See Also

You can restart execution from break mode.  Restarting returns the code to a newly initialized state, resetting all variables and removing any suspended procedures from memory.

To restart execution, choose Restart from the Run menu.


See Also

Continuing Execution

Debugging Checklist

Ending Execution

Starting Execution

Stopping Execution


Searching for Text in Code

See Also

To search for specific text in a module

1.	From the Edit menu, choose Find.

The Find dialog box appears.

2.	In the Find What box, type the text you want to search for (if you didn't select the text before displaying the dialog box).

3.	Select a Search option button to specify where to look for the text.

4.	Select a direction from Direction list box to specify the direction of the search

5.	To set limits on the search:

Select Find Whole Words Only to search for the complete word by itself and not as part of another word.

Select Match Case to find an exact match.

Select Use Pattern Matching to use wildcards or ranges.

6.	Choose Find Next.


See Also

Find Command (Edit Menu)

Replacing Text in Code


Setting and Clearing Breakpoints

See Also

You set a breakpoint to suspend execution at a specific statement in a procedure; for example, where you suspect problems may exist.  You clear breakpoints when you no longer need them to stop 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 Run menu, choose Toggle Breakpoint (F9), or use the toolbar shortcut:

The breakpoint is added and the line is set to the breakpoint color defined in the Editor tab of the Options dialog box.

To clear a breakpoint

1.	Position the insertion point anywhere on a line of the procedure containing the breakpoint.

2.	From the Run menu, choose Toggle Breakpoint (F9).

The breakpoint is cleared and highlighting is removed.

To clear all breakpoints in the application

From the Run menu, choose Clear All Breakpoints.

Note   Breakpoints set in code are not saved when you save your code.

If you set a breakpoint on a line that contains several statements separated by colons (:), the break always occurs at the first statement on the line.


See Also

Adding Watch Expressions

Debugging Checklist

Deleting Watch Expressions

Editing Watch Expressions

Editor Options Tab


Starting Execution

See Also

One way to test your code is to run it and work with it as a user would.

To start execution, choose Start (F5) from the Run menu.

If your application doesn't run, it may be because:

A syntax error or some other error exists in your code.

A  logic error exists in your code, which may result in a run-time error.

To get Help, choose the Help button or press F1 while the error message is displayed.  Consider the suggestions provided to correct the error before you run your code again.

Note   It is good programming practice to save before you run.  You can automatically save your work before you run by selecting Save Before Run, Don't Prompt on the Environment tab of the Options dialog box.


See Also

Continuing Execution

Debugging Checklist

End Statement

Ending Execution

Environment Options Tab

Restarting Execution

Stopping Execution


Tracing Execution

See Also

You trace execution because it may not always be obvious which statement is executed first.  Use these techniques to trace the execution of code:

Step Into [image] traces through each line of code and steps into procedures.  This allows you to view the effect of each statement on variables.

Step Over [image] executes each procedure as if it were a single statement.  Use this instead of Step Into to step across procedure calls rather than into the called procedure.

Step To Cursor [image] allows you to select a statement further down in your code where you want execution to stop.  This allows you to "step over" sections of code, for instance, large loops.

To trace execution from the current statement

From the Run menu, choose Step Into (F8), or use the toolbar shortcut:

From the Run menu, choose Step Over (SHIFT+F8), or use the toolbar shortcut:

From the Run menu, choose Step To Cursor (CTRL+F8).

To trace execution from the beginning of the program in break mode

From the Run menu, choose Step Into (F8), Step Over (SHIFT+F8), or Step To Cursor (CTRL+F8).


See Also

Debugging Checklist

Setting and Clearing Breakpoints

Step Into, Step Over, Step To Cursor Commands (Run Menu)


Turning Syntax Checking On or Off

See Also

Visual Basic includes a syntax-checking feature that:

Checks each statement 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 time.

This feature is turned on when you first start, but you can turn it off if you prefer to write code without being alerted to errors as they occur.

To display syntax errors

1.	From the Tools menu, choose Options.

2.	Select the Environment tab.

3.	Select the Auto Syntax Check check box.

4.	Choose OK.


See Also

Entering and Editing Code

Environment Options Tab


Using Example Code from Help

See Also

You can copy example code from online Help, paste it into the current module, and then edit the code to fit your needs.

To copy and paste example code

1.	Find the topic you want.

2.	Click the word Example in the nonscrolling region of the topic to jump to the code example.

3.	In the secondary window that contains the code example, choose Copy.

4.	In the Copy window, select the code you want to copy and choose the Copy button.

5.	In the module, place the insertion point where you want to paste the example code.

6.	From the Edit menu, choose Paste.

Note   After copying example code from Help, you may need to modify variables, constants, and references.  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 properly.


See Also

Entering and Editing Code

Replacing Text in Code


Using Instant Watch

See Also

In break mode, you may want to check the current value of a 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.	Select an expression in the module where it resides.

2.	From the Tools menu, choose Instant Watch (SHIFT+F9).

The Instant Watch dialog box displays the current value of the expression you selected.

 Or

Click the right mouse button and choose Instant Watch from the context menu.

3.	If you want to add a watch expression based on the expression in the Instant Watch dialog box, choose Add.


See Also

Adding Watch Expressions

Debugging Checklist

Deleting Watch Expressions

Editing Watch Expressions

Instant Watch Dialog Box

Setting and Clearing Breakpoints


Managing Versions of Your Application

See Also

You may create and distribute more than one version of an application.  The existence of multiple versions of an application can cause problems if the various versions are not managed properly.  Such problems include:

Version incompatibilities in OLE servers.

Copying of an older version of a file used by your application during setup.

Versioning in OLE Servers

In OLE servers, changes you make to existing procedures may cause the new version to be incompatible with previous versions.  For example, you could change:

The name of a procedure.

The number of arguments passed to a procedure.

The data type of arguments passed to a procedure.

For code written to use previous versions of the OLE server, such changes may cause errors.  Visual Basic gives you a way to define a version of your application as a reference to which your changes are compared.  This reference version is called the compatible OLE server.  If you make a change that might cause incompatibility with the compatible OLE server, Visual Basic displays a warning message to alert you to the possible incompatibility.

To specify a compatible OLE server

1.	From the Tools menu, choose Options.

The Options dialog box appears.

2.	Select the Project tab.

3.	In the Compatible OLE Server field, enter the full path and filename of the .EXE file you want to use as the basis for identifying possible version incompatibilities.

4.	Choose OK.

Versioning of an .EXE File

Windows-based applications can contain an internal resource that provides information about the version of the application.  Your setup program can use the information in this resource to determine if the version of the .EXE file being installed is newer than another version that might already be on the user's system.  Users can view version information about your application in the Windows File Manager by selecting the .EXE file, and then pressing ALT+ENTER.  Visual Basic provides a dialog box where you specify version information that you want to include in the created .EXE file.

To specify version information when making an .EXE File

1.	From the File menu, choose Make EXE File.

The Make EXE File dialog box appears.

2.	Choose the Options button.

The EXE Options dialog box appears.

3.	Under the Application section, enter the Title of the application or accept the default project name.  Select the icon you want to use to represent the application from the form icons listed in the Icon combo box.

4.	In the Version Number section of the dialog box, enter the major, minor, and revision number for the .EXE file.

If you select the Auto Increment check box, Visual Basic automatically increases the value in the Revision text box each time you run the Make EXE File command for this project.

5.	In the Version Information section of the dialog box, select a type of version information from the Type list box.

6.	Enter the value for the selected version information type in the Value text box.

Repeat Steps 4 and 5 as necessary to specify all the desired version information.  You can specify text for:

Comments

Company Name

File Description

Legal Copyright

Legal Trademarks

Product Name

7.	Choose OK.

The Make EXE File dialog box appears again.

8.	Choose OK to make the .EXE file.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.


See Also

Creating an OLE Server

EXE Options Dialog Box

Make OLE DLL File Command

Modifying SETUP.LST

Project Options Tab

Where to Install Files on the User's Machine


Graphical Objects

See Also

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 PictureBox 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 become visible.  (Note, however, that the Image control doesn't have a BackStyle property.)  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

Circle Method

hWnd Property

Image Control

Label Control

Line Control

Line Method

Print Method

Shape Control


Using Resource Files

See Also

When you are writing Visual Basic code, you can use a resource file in place of string literals, pictures, and data.  You access resources in a resource file with the LoadResString, LoadResPicture, and LoadResData functions.  Storing such elements in a resource file offers two benefits:

Performance and capacity are increased because strings, bitmaps, icons, and data can be loaded on demand from the resource file, instead of all being loaded at once when a form or a module is loaded.

If you are writing an application that will be distributed in foreign markets, the resources that need to be translated are isolated in one resource file. Also, there is no need to access the source code or recompile the application.

You can have only one resource file in your project. If you attempt to add more than one resource file, Visual Basic generates an error message.

To create a resource file

1.	Create a resource source file (*.RC) that contains all the string resources of your application.

The syntax for creating the resource source file is documented in the Windows Software Development Kit, as well as on the Microsoft Developer Network CD. You must associate an identifier (ID) with each resource, and then reference each ID in your code.

2.	Use a resource compiler to convert the resource source file into a resource file (*.RES). You can use the resource compiler shipped with Microsoft Visual C++ to convert the source file.

Note   In Visual Basic, the resource whose ID is 1 is reserved for the application icon. Therefore, you can't have a resource in your .RES file with that ID number. Visual Basic generates an error message if your code attempts to load that resource ID.

To add a resource file to your project

1.	From the File menu, choose Add File.

2.	In the Add File dialog box, select Resource Files (*.RES) in the List Files of Type box.

3.	Select the resource file you want to add to the project, and choose OK to close the Add File dialog box.

Visual Basic recognizes resource files by the .RES filename extension.  If the resource file doesn't have the appropriate filename extension, Visual Basic won't load it. Conversely, if any file uses the .RES filename extension, Visual Basic interprets that it is a resource file when adding it to the project.  If the file doesn't follow the standard format for a resource file, Visual Basic generates an error message the first time you attempt to use the resource file support functions (LoadResString, LoadResPicture, and LoadResData), or when you try to make an .EXE file.  Visual Basic generates the same error message if you try to add a 16-bit resource file to a 32-bit project, and vice versa.

Once the resource file is added to the project, the View Form and View Code buttons in the Project Window are disabled when the file is selected.  This is because the file is still considered a standard resource, as if it were created or used by Microsoft Visual C++ and most other Windows [image] based development tools, and it can't be edited in Visual Basic.

When you choose Make EXE File from the File menu, Visual Basic compiles all resources in the resource file into the .EXE file.  The .RES file, before and after you compile the .EXE file, is a standard Windows resource file, which means the resources contained in the file can be loaded in any standard Windows [image] based resource editor.

Locking Resource Files

Visual Basic uses file locking on the .RES file to prevent problems with multiple applications trying to use the file at the same time. Visual Basic locks the .RES file whenever:

Visual Basic is in run or break mode.

You create an .EXE file.  The .RES file is locked while Visual Basic makes the .EXE file.


See Also

LoadResData Function

LoadResPicture Function

LoadResString Function


Control Arrays

See Also

A control array is a group of controls that share the same Name, type, and event procedures.  A control array has at least one element and can grow to as many as elements as your system resources and memory permit, and the size also depends on how much memory and Windows resources each control requires.  The maximum index you can use in a control array is 32767 with 32-bit Windows platforms, and approximately 16000 with 16-bit Windows platforms.

Elements of the same control array have their own property settings. Common uses for control arrays include Menu controls and groups of OptionButton controls.

Control arrays are useful if you want several controls to share code.  For example, if you create three OptionButton controls as a control array, the same code executes regardless of which button receives the Click event.

If you want to create a new control at run time, that control must be a member of an existing control array.  With a control array, each new element inherits the common event procedures of the array.

Without the control array mechanism, creating new controls at run time isn't possible, because a completely new control would not have any predefined event procedures.  Control arrays solve this problem, because each new control inherits the common event procedures already written for the array.  For example, if your form has several TextBox controls that each receive a date value, you can set up a control array so that all of the TextBox controls share the same validation code.


See Also

Adding and Deleting Controls at Run Time

Creating a Control Array

Creating a Menu Bar

Creating a Menu Control Array

Index Property (Control Array)

Name Property


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 for the Name property.

Note   To remove a control from a control array without deleting the control, change the control's Name property, and delete or reset the Index property, depending on if the control is to be part of a new control array.

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)."

To add a control array element by changing its name

1.	Draw the controls you want to be in the control array.  (The controls must all be of the same type.)  Decide which control will become the first element in the array.

2.	Select one of the controls and change the setting of its Name property to the setting of the Name property for the first element in the array.

3.	When you type an existing Name property value for a control in the array, Visual Basic displays a dialog box asking you to confirm that you want to create a control array.  Choose Yes to confirm the action.

Controls added this way share only their Name property and control type; all other properties remain the same as when the control was originally drawn.

To add a control array element by copying an existing control

1.	Draw a control in the control array.

2.	While the control has the focus, choose Copy from the Edit menu.

3.	From the Edit menu, choose Paste.  Visual Basic displays a dialog box asking you to confirm that you want to create a control array.  Choose Yes to confirm the action.

This control is assigned an index value of 1.  The first control you drew has a value of 0.

The index value of each new array element corresponds to the order in which the element was added to the control array.  When controls are added this way, most of the visual properties, such as Height, Width, and color properties, are copied from the first control in the control array to the new controls.  Therefore, it is recommended that you set all of the properties for the first control, such as the Height, Width, color and font properties, before you copy and past the rest of the array elements.


See Also

Adding and Deleting Controls at Run Time

Control Arrays

Index Property (Control Array)

Name Property


Adding and Deleting Controls at Run Time

See Also

You can add and remove controls in a control array at run time using the Load and Unload statements.  However, the control to be added must be an element of an existing control array.  You must have created a control at design time with the Index property set, probably to 0.

When you load a new element of a control array, most of the property settings are copied from the lowest existing element in the array.  The Visible, Index, and TabIndex property settings are not automatically copied to new elements of a control array, so to make the newly added control visible, you must set its Visible property to True.

Note   Visual Basic generates an error if you attempt to use the Load statement with an index number already in use in the array.

You can use the Unload statement to remove any control created with Load.  However, you can't use Unload to remove controls created at design time, regardless of whether or not they are part of a control array.


See Also

Control Arrays

Creating a Control Array

Index Property (Control Array)

Load Statement

Unload Statement


Adding and Deleting Controls at Run Time Example

This example shows how to add and delete controls at run time.  To try this example, paste the code into the Declarations section of a Form containing one OptionButton control, two CommandButton controls, and a large PictureBox control.

Set the Index property for the OptionButton to 0 to create a control array.  Set the Caption property to "Add" for one CommandButton and "Delete" for the other.  Then press F5.  Each time an OptionButton is clicked, the BackColor property of the PictureBox is reset.  Clicking a CommandButton causes an OptionButton 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


OLE Controls Interoperability for 16- and 32-Bit Platforms

The following table identifies when you can load 16-bit in-process objects into a 16-bit or 32-bit version of Visual Basic running with various platforms.  In-process objects run in the container's process space.  Cross-process objects allow marshaling, which allows pointers to interfaces to be passed through remote procedure calls and enables controlling applications in other processes to access and manipulate objects across boundaries.

Visual Basic/Platform	16-bit in-process control	16-bit in-process embedded object	16-bit in-process OLE Automation object
16-bit Visual Basic with 16-bit Windows	Yes	Yes	Yes
16-bit Visual Basic with Windows NT	Yes	Yes	Yes
16-bit Visual Basic with Windows 95	Yes	Yes	Yes
32-bit Visual Basic with Windows NT	No	No	No
32-bit Visual Basic with Windows 95	No	No	No
The following table identifies when you can load 32-bit in-process objects into a 16-bit or 32-bit version of Visual Basic with various platforms.

Visual Basic/Platform	32-bit in-process control	32-bit in-process embedded object	32-bit in-process OLE Automation object
16-bit Visual Basic with 16-bit Windows	No	No	No
16-bit Visual Basic with Windows NT	No	No	No
16-bit Visual Basic with  Windows 95	No	No	No
32-bit Visual Basic with Windows NT	Yes	Yes	Yes
32-bit Visual Basic with Windows 95	Yes	Yes	Yes
The following table identifies when you can load 16-bit cross-process objects into a 16-bit or 32-bit version of Visual Basic running with various platforms.

Visual Basic/Platform	16-bit cross-process control	16-bit cross-process embedded object	16-bit cross-process OLE Automation object
16-bit Visual Basic with 16-bit Windows	No	Yes	Yes
16-bit Visual Basic with Windows NT	No	Yes	Yes
16-bit Visual Basic with  Windows 95	No	Yes	Yes
32-bit Visual Basic with Windows NT	No	Yes	Yes
32-bit Visual Basic with Windows 95	No	Yes	Yes
The following table identifies when you can load 32-bit cross-process objects into a 16-bit or 32-bit version of Visual Basic running with various platforms.  All 32-bit cross-process objects can be used in 16-bit Windows if the objects are written to Win32S and run with Win32S.  In this case, refer to the information for loading 32-bit cross-process objects into a 16-bit version of Visual Basic with Windows NT instead of in a 16-bit Visual Basic version with 16-bit Windows.

Visual Basic/Platform	32-bit cross-process control	32-bit cross-process embedded object	32-bit cross-process OLE Automation object
16-bit Visual Basic with 16-bit Windows	No	No	No
16-bit Visual Basic with Windows NT	No	Yes¹	Yes
16-bit Visual Basic with  Windows 95	No	Yes¹	Yes
32-bit Visual Basic with Windows NT	No	Yes	Yes
32-bit Visual Basic with Windows 95	No	Yes	Yes
¹  These objects can be used as indicated, but they can't be added to the Custom Controls dialog box using the Browse button.


Accessing Screen Properties

See Also

You can use Screen properties to help your application scale itself properly for an end-user's screen resolution.  Like Form objects 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 can't 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

For example, Screen.Width.


See Also

App Object

Clipboard Object

Debug Object

Form Object

Printer Object, Printers Collection

Screen Object


Calling Windows API Functions

See Also

The Visual Basic, Professional Edition provides information on the Microsoft Windows Application Programming Interface (API) in several files located in the \WINAPI subdirectory of your Visual Basic directory.

The WIN31API.TXT file contains function declarations, Type declarations, and the values for global constants used in the functions for 16-bit Windows API. The WIN31WH.HLP file documents each function in terms of the C programming language.  This file is found only in 16-bit versions of Visual Basic.

The WIN32API.TXT file contains function declarations, Type declarations, and the values for global constants used in the functions for the 32-bit Windows API.

The WINMMSYS.TXT file contains declarations and global symbolic constants for Windows 3.1 multimedia API functions.

API Viewer provides access to the WIN31API.TXT, WIN32API.TXT, and WINMMSYS.TXT files, and you can use it to copy and paste API functions into your Visual Basic code.

Note   To install the API Viewer on your machine, you should select the Windows API Reference option during setup.

To use the API Viewer

1.	Open the API Viewer by double-clicking the API Viewer icon in the Visual Basic program group.

2.	From the File menu, choose Load Text File.

3.	Open either WIN31API.TXT (16-bit Windows declares, types, and constants), or WIN32API.TXT (32-bit Windows declares, types, and constants), which are located in the \WINAPI subdirectory of the main Visual Basic directory.

4.	In the API Type drop-down list box, select Declares, Constants, or Types to view items in the Available Items box.

5.	Select an item you want to add to your Visual Basic project from the Available Items box, and then choose the Add button.  The item is added to the Selected Items list.  Be sure to find whether the function requires a STRUCT (or structure) requiring a Type declaration or any constant declaration in Visual Basic.

6.	Once you have selected all of the items you want to include in your code, choose the Copy button to copy all of those items in the Selected Items box onto the Clipboard.

7.	Open your Visual Basic project, place the insertion point where you want to paste the declarations, constants, and/or types (in the Declarations section of a module), and then choose Paste from the Edit menu.

Warning   You must be very careful to provide arguments of the correct data type.  The wrong data type may cause a General Protection Fault at run time.

Because some of the library names and data types are different for 16-bit and 32-bit Windows API functions, you need to use conditional compilation if you are writing an application that will be used on 16-bit and 32-bit Windows platforms.  For example, if you use the GetClassName API function, you can use the following code:

# If Win32 Then	' 32-bit VB uses this Declare.

Declare Function OSGetClassName Lib "User32" Alias _

"GetClassNameA" (ByVal hWnd As Long, ByVal lpClassName As String, _

ByVal nMaxCount As Long) As Long

# Else	' 16-bit VB uses this Declare.

Declare Function OSGetClassName Lib "User" Alias "GetClassName" _

(ByVal hWnd As Integer, ByVal lpClassName As String, ByVal _

nMaxCount As Integer) As Integer

# End If

When you compile the preceding code using the 32-bit version of Visual Basic, the value of the conditional compilation constant Win32 is True, and therefore compiles with the 32-bit declaration.  When you compile the same source code using the 16-bit version of Visual Basic, the value of the conditional compilation constant Win32 is False, and therefore compiles with the 16-bit declaration.

In addition to Win32, there is a Win16 conditional compilation constant.  When the Win32 constant is True, the Win16 constant is False and vice versa.


See Also

Call Statement

Declare Statement

Advanced Options Tab


Creating an OLE Server

See Also

OLE servers give you the ability to define classes that other applications can manipulate using standard Visual Basic syntax.  The classes defined in an OLE server can have their own properties and methods.  Depending on the options you choose to implement, the classes can be used just by the application in which they are defined, or they can be exposed for use by other applications.

To create an OLE server

1.	Decide what objects you need to define and their relationship to one another.  You also need to decide just what properties and methods each of your classes must have.

2.	Define the individual classes in the OLE server.

3.	In the Project tab of the Options dialog box, set the Project Name, StartMode, and Application Description options for the OLE server.

4.	Prepare the initialization of the OLE server.  If the OLE server doesn't display any forms and only provides access to the objects in code, set the Startup Form option in the Project tab of the Options dialog box to Sub Main.  Any initializing code for the OLE server should go in a Sub Main procedure in a standard module.


See Also

Defining a Class in an OLE Server

Managing Versions of Your Application

Project Options Tab


Defining a Class in an OLE Server

See Also

You use ClassModule objects to define classes and their properties and methods in an OLE server.  A ClassModule defines a single class and therefore you create a ClassModule for each class you want to define.  The code you write in each ClassModule defines the properties and methods of that class.

To define a class in an OLE server

1.	Open the project you use to create the OLE server.

2.	From the Insert menu, choose Class Module.

Visual Basic inserts a ClassModule into the project and displays the Code window for that ClassModule.

3.	To make the class available outside the project, set the ClassModule object's Public property to True.  The default value of this property is False, meaning the classes are available only within the project containing the ClassModule.

4.	To determine how to create instances of a class in a public ClassModule, set the ClassModule object's Instancing property in the Properties window.  The default value of this property is 0, meaning an instance of that class can't be created by external applications.

Notes   A class defined in a ClassModule is always creatable within the same project regardless of the setting of the Instancing property.  When you set the Public property to False, Visual Basic ignores the Instancing property.

5.	Set the Name property for the ClassModule in the Properties window.  The value of the Name property determines how OLE Automation controllers identify the class.

6.	In the ClassModule, write the necessary code to provide the desired properties and methods of the class.  To create a property for a class, you can declare a public variable in the ClassModule.  For example, intBankBalance could be the property of a class you create:

Dim intBankBalance As Integer

Public variables provide an easy way to implement simple properties.  However, you can't assign Help topics to public variables.

You can also use Property procedures, which return and assign values and set references to objects in addition to executing code when you read or write the property.  You can also assign Help topics to properties defined with Property procedures.

Then, to define a method for the class, you can use a Sub or Function procedure with the Public keyword.  For example, to create the PrintExceptions method for a class, add a public Sub procedure to that class module:

Public Sub PrintExceptions (FirstArgument, SecondArgument)

' Statements here.

End Sub

7.	If desired, use the Member Options dialog box (available from the Object Browser) to set the Description and HelpContextID for the classes, methods, and Property procedures you create.


See Also

ClassModule Object

Instancing Property

Creating an OLE Server

Member Options Dialog Box

Name Property

Property Get Statement

Property Let Statement

Property Set Statement

Public Property

Setting Member Options


Setting Member Options

See Also

When you create an OLE server, users of that application can use the Object Browser to get information about the public members of the application (classes, properties, and methods).  The exposed classes, properties, and methods automatically appear in the Object Browser when it is used to browse your OLE server.  By setting additional properties of the members of an OLE server, you can also provide:

Descriptive text about members of the application in the Object Browser through the Description property.

Support for context-sensitive Help on members of the application from the Object Browser through the HelpContextID property.

Note   You can only set these two properties for public methods, Property procedures, and classes.  You can't set these properties for properties defined simply as data members.

To set OLE server member options

1.	Open the project for the OLE server and display the Object Browser.

2.	Choose your project in the Libraries/Projects list box.

3.	Select a class, property, or method in your project.

4.	Choose the Options button.

The Member Options dialog box appears.

5.	Enter a descriptive string in the Description text box.  This string appears in the Object Browser when the member is selected.

6.	Enter a numeric value for the HelpContextID property.  The Help file that is displayed is the file specified in the Project tab of the Options dialog box.


See Also

Creating an OLE Server

Defining a Class in an OLE Server

Member Options Dialog Box

Project Options Tab


Using Custom Controls

See Also

Custom controls exist as separate files with either a .VBX or .OCX filename extension.  They include specialized controls, such as the CommonDialog control and third-party custom controls, as well as enhanced versions of standard controls, such as the DBList and DBCombo controls.

Custom controls with the .OCX filename extension take advantage of OLE technology.  Custom controls with the .VBX filename extension use older technology and are found in applications written in earlier versions of Visual Basic.

Note   You can continue to use .VBX custom controls with the 16-bit version of Visual Basic.  You can't use these controls in the 32-bit version of Visual Basic.

You can use .OCX controls in both 16-bit and 32-bit versions of Visual Basic; however, you need to use 16-bit .OCX controls with the 16-bit version of Visual Basic, and 32-bit .OCX controls with the 32-bit version of Visual Basic.

When Visual Basic opens a project containing a .VBX control, the default behavior is to replace the .VBX control with an .OCX control, but only if an .OCX version of the control is available.

To see a list of the custom controls included in your project

From the Tools menu, choose Custom Controls.  The checked boxes in the Available Controls box indicate the .VBX controls, .OCX controls, and insertable objects included in your project.

To add a custom control

1.	From the Tools menu, choose Custom Controls.

2.	Under Show, select the Insertable Objects and Controls options.

3.	Select the check box next to the name of each .OCX control, .VBX control, or insertable object you want to add, and then choose OK.  Once a custom control is placed in the Toolbox, you can add it to a Form just as you would with a standard control.

If the .OCX control, .VBX control, or insertable object that you want to use isn't listed in the Available Controls box, choose the Browse button to locate the file.

To remove a custom control

1.	Remove all instances of the control from the forms in your project.  Delete any references to the control in the project's code.  If references to a deleted control are left in your code, an error message is displayed when you compile the application.

2.	From the Tools menu, choose Custom Controls.

3.	Clear the check box next to the name of the .VBX control, .OCX control, or insertable object, and then choose OK.  An error message appears if there are remaining instances of the control in your project's forms.


See Also

Custom Control Upgrade Dialog Box

Custom Controls Dialog Box

Using Externally Creatable Objects


Using Externally Creatable Objects

See Also

You can create a reference to some objects, such as a Microsoft Excel Application object, in code.  An object is an externally creatable object if you can set a reference to it with the New keyword (for applications that support this), CreateObject, or GetObject from outside the OLE server that created it.  Other objects, such as a Microsoft Excel Button object, are dependent objects because they can be accessed only by using a method of a higher-level object.  For example, the Cells method of the Microsoft Excel Worksheet object returns a Range object.

Some objects, such as a Microsoft Word document, are visible to the user, and you can insert them in a Form or embed them in a compound document file.  Other objects, such as Printer objects and Database objects, can't be inserted because they have no visible representation that can be seen on a Form.  Objects that are insertable can be thought of as custom controls.  You can add these to the Toolbox and use them as you would use other Visual Basic controls.

Because most top-level objects are externally creatable, you can get a direct reference to them.  Later, if you need to access a dependent object, you can get a reference to it from an externally creatable object.

To get a reference to externally creatable objects

1.	Create storage for a variable of an object type.  How you do this depends on whether the OLE server supplies an object library.

2.	Set the variable to reference a new object or an existing object.

3.	Write code using the object's methods and properties.

4.	Release the object variable when you are finished using the object.  You can do this by setting the variable to Nothing or by causing it to lose scope.


See Also

Checking an Application for an Object Library

CreateObject Function

GetObject Function

New Keyword

Nothing Keyword

Using Custom Controls


Checking an Application for an Object Library

See Also

If you use the objects in other applications as part of your Visual Basic application, you may want to establish a reference to the object libraries of those applications.  Before you can do that, you must first be sure that the application provides an object library.

To see if an application provides an object library

1.	From the Tools menu, choose References to display the References dialog box.

2.	Scroll through the list for the application whose object library you want to reference.  The dialog box shows all object libraries registered with the operating system.  If it isn't listed, then you can use the Browse button to search for type libraries (*.OLB and *.TLB) or executable files (*.EXE and *.DLL).

3.	Select the reference in the Available References box, and choose OK.

Your Visual Basic project now has a reference to the application's object library.  If you open the Object Browser (press F2) and select the application's library, it displays the objects provided by the selected object library, as well as each object's methods and properties.  In the Object Browser, you can select a method or property in the Methods/Properties box and choose Paste to automatically add the syntax to your code.


See Also

References Dialog Box

Using Externally Creatable Objects


Working with OLE Automation Objects

See Also

The following table summarizes various ways you can work with OLE Automation objects in Visual Basic:

To	Do This
Determine whether an application offers an object library.	Use the References dialog box from the Tools menu.  If the OLE server appears in the References dialog box, the application has an object library.
Reference an externally creatable object from an application that provides an object library.	Use the References dialog box to add a reference to the object library and then use the Dim and Set statements to create a variable that refers to the object.
Reference an externally creatable object from an application that doesn't provide an object library.	Use the CreateObject function to get a reference to an object.
Reference a dependent object.	Use a method from a higher-level object in the hierarchy.
Get an existing object from an application.	Use the GetObject function to get a reference to an existing instance of an object.
Use an object's methods and properties.	Use the standard object.method or object.property syntax.
Release an object.	Set the object variable to Nothing.


See Also

Checking an Application for an Object Library

CreateObject Function

Dim Statement

GetObject Function

New Keyword

Nothing Keyword

Set Statement

Using Externally Creatable Objects


What's New in Version 4.0

Visual Basic, Applications Edition

Visual Basic, Applications Edition, version 2.0 has been added as the language engine in Visual Basic.  This version is fully compatible with earlier versions of the stand-alone Visual Basic product, and with Visual Basic, Applications Edition, version 1.0, which is included in Microsoft Excel version 5.0 and Microsoft Project version 4.0.  The inclusion of Visual Basic, Applications Edition makes it easier to program OLE Automation objects and means that Visual Basic code can be easily moved between modules in the applications that support OLE Automation.

OLE Automation

Using OLE Automation in Visual Basic, you can "borrow" the functionality of other applications by controlling their objects from within your Visual Basic application.  If the object is an OLE Automation object, you can use its properties and methods in code. Each OLE Automation object is a building block you can use in code to collect and expose data and functions from other applications in a way that makes sense in your application.  For example, you can build an application that uses Microsoft Excel as a calculation engine, and in which reports are created in Microsoft Word documents.  You can also add objects, such as a Microsoft Excel Chart, directly to the Toolbox for easy drag-and-drop access.

Reusable Objects and Collections

You can create reusable objects, with their own properties and methods, and assemble them into an object model.  The definitions of these objects are called classes, and are contained in Visual Basic's new class modules.  You can even create your own collections, built using Visual Basic's new Collection object.

Enhanced Development Environment

You can use context or pop-up menus for forms, controls, and code, and attach add-ins for source code control and other features.  With the Professional Edition, you can even create your own add-ins.

Property Procedures

Property procedures allow you to add custom properties to form, standard, and class modules, and to execute code when the property is set or retrieved.  For example, you could add an Inverted property to a form.  When Inverted is set to True, the code in the associated Property procedure invokes an API to invert a bitmap on the form.

Object Browser

The Object Browser presents a hierarchical display of all the classes, properties, and methods available to your application from Visual Basic and other OLE components.  This allows you to easily select objects and cut and paste them into your code.

32-Bit Support and Conditional Compilation

With conditional compilation, you can embed platform-specific code segments in #If...Then...#Else statements, and selectively build 16-bit and 32-bit versions of your application from one code base.  The 32-bit version of Visual Basic supports long filenames in all project components and relaxes most of the 64K capacity constraints for properties and the Visual Basic language.

New Data-Bound Controls

You can bind data to more controls, including the new DBList, DBCombo, and DBGrid controls.  The OLE container control is also data-bound.  These provide automatic list management and instantaneous read-write access to external data.

Jet 2.5 and 3.0

The Microsoft Jet 2.5 (16-bit) and 3.0 (32-bit) database engines provide many new features, including a new Data Access Objects (DAO) programming model, cascading updates and deletes, programmatic access to referential integrity, and improved speed for many queries.  If you have a copy of Microsoft Access, you can also establish and modify security settings in a Microsoft Jet database.  Jet 2.5 and 3.0 are functionally compatible, so you can create both 32-bit and 16-bit database applications from the same code, simply by switching engines and recompiling.  (To create 32-bit applications you must use one of Microsoft's 32-bit operating systems, Windows 95 or Windows NT)  In addition, the Jet 3.0 engine supports database replication, and direct manipulation of replicated databases from within Visual Basic code.

New Project File Extension

To distinguish Visual Basic project files from source files used by other development tools, the file extension for Visual Basic project files has changed from .MAK to .VBP.

Windows 95 Custom Controls

The Windows 95 custom controls enable you to create applications with the Windows 95 interface look and feel.  For example, your applications can incorporate list views, tree views, a status bar, toolbars, and tabbed dialog boxes.  In addition, the RichTextBox is an extensively featured RTF text editor with drag and drop capability.  Use the Slider control to allow users a new way of entering data.  The Windows 95 custom controls will give your applications myriad new possibilities.  For more information, see the Custom Control Reference.

Enterprise Edition

The Enterprise Edition of Visual Basic includes new features designed to give developers the means to build client/server applications that manage business-critical data.  Remote Automation, for example, allows you to create shared, reusable components that use the OLE Automation interface for network communication.  You will find a suite of tools designed specifically for client/server development, including utilities to catalog, install and configure components, and to manage source code access.  The Enterprise Edition also offers a conceptual framework and practical guidelines for structuring development and deployment of your component-based applications.

Remote Data Objects (RDO) and the RemoteData Control (RDC) permit applications to access ODBC-accessible data sources without using a local query processor.  This can mean significantly higher performance and more flexibility when accessing remote client/server database engines.  Although the RDO and RDC can access any ODBC data source, they are designed and tuned to take advantage of database servers that use sophisticated query engines like Microsoft SQL Server and Oracle.


Connecting to the SourceSafe Add-In

See Also

You have access to the four major source code control program commands within the Visual Basic development environment.  When you connect to the SourceSafe add-in and you either use Open SourceSafe Project to download a project from SourceSafe into Visual Basic, or Add Files to SourceSafe to add your current project into SourceSafe, you activate the Get, Check In, Check Out, and Undo Check Out commands on the Tools menu.  You also gain access to several SourceSafe commands on the Add-Ins menu.

Note   The SourceSafe add-in is provided only with the Visual Basic, Enterprise Edition.

To connect to the SourceSafe add-in

1.	From the Add-Ins menu, choose Add-In Manager.

2.	In the Available References box, select the Source Code Control add-in.

Note   If the SourceSafe add-in is not listed in the Available References list, you probably need to perform the Client installation of SourceSafe, which has a separate installation from Visual Basic.  See the following procedure for more information.

3.	Choose OK.

The SourceSafe menu and its submenus should appear on the Add-Ins menu.

Installing SourceSafe

Typically, the Server installation is performed first on a remote machine that will be used as the server for your SourceSafe project; for more information on the Server installation, see the Introduction in the Visual SourceSafe User Guide.  Then, to use the SourceSafe add-in in the Visual Basic development environment, you must perform the Client SourceSafe installation on your local machine.

To install SourceSafe on your local machine

1.	Insert the compact disc in the CD-ROM drive.

2.	Run the SourceSafe setup program, SETUP.EXE, which is available in the SourceSafe root directory on the compact disc.

Note   Before performing the Client installation of SourceSafe, you must first install Visual Basic.

3.	Follow the instructions on the screen, and make sure to perform a Client installation, not a Server or Custom installation.

If you want to use all of the features of SourceSafe, you can use the stand-alone product provided with the Enterprise Edition.


See Also

Add-In Manager Dialog Box

Check In Command (Tools Menu)

Check Out Command (Tools Menu)

Get Command (Tools Menu)

Undo Check Out Command (Tools Menu)


Using Constants

See Also

Often you'll find that your code contains constant values that reappear over and over.  Or you may find that the code depends on certain numbers that are difficult to remember and may have no obvious meaning.

In these cases, you can make your code easier to read and maintain by using constants.  A constant is a meaningful name that takes the place of a number or string that does not change.  Although a constant somewhat resembles a variable, you can't modify a constant or assign a new value to it as you can to a variable.

Sources for Constants

There are two sources for constants:

Intrinsic or system-defined constants are provided by applications and controls.  Other applications that provide object libraries, such as Microsoft Excel and Microsoft Project, also provide a list of constants you can use with their objects, methods, and properties.  You can get a list of the provided constants for individual object libraries in the Object Browser.

Visual Basic constants are listed in the Visual Basic (VB), Visual Basic for applications (VBA), and data access (DAO) object libraries.

Symbolic or user-defined constants are declared using the Const statement.

In earlier versions of Visual Basic, constant names were capitalized with underscores.  For example:

TILE_HORIZONTAL

Note   Visual Basic version 4.0 recognizes constants in applications created in earlier versions of Visual Basic.  You can choose to upgrade your constants to those listed in the Object Browser.  Constants listed in the Object Browser don't need to be declared in your application.

In Visual Basic version 4.0, intrinsic constants are qualified to avoid confusing constants with the same name that exist in different object libraries, and which may have different values assigned to them.  There are two ways to qualify constant names:

By prefix

By library reference

Qualifying Constants by Prefix

The intrinsic constants supplied by all objects appear in a mixed-case format, with a two-character prefix indicating the object library that defines the constant.  Constants from the Visual Basic and Visual Basic for Applications object libraries are prefaced with "vb"; constants from the Data Access object library are prefaced with "db"; and constants from the Microsoft Excel object library are prefaced with "xl".  The prefixes for custom controls vary, depending on the type library.  For example:

vbTileHorizontal

dbAppendOnly

xlDialogBorder

grdAlignCenter

Qualifying Constants by Library Reference

You can also qualify the reference to a constant with the following syntax:

[libname.][modulename.]constname

The syntax for qualifying constants has these parts:

Part	Description

libname	The name of the type library that defines the constant.  For most custom controls, this is also the class name of the control.  If you don't remember the class name of the control, position the mouse pointer over the control in the Toolbox.  The class name appears in the displayed tool tip.

modulename	The name of the module within the type library that defines the constant.  You can find the name of the module using the Object Browser.

constname	The name defined for the constant in the type library.

For example:

Threed.LeftJustify


See Also

Const Statement

Object Browser


Start With Full Compile (Run Menu)

See Also

Runs the application from the startup form (or Sub Main) specified in the Project tab of the Options dialog box.  All forms being designed are closed, variables are initialized, and the startup form (if any) is loaded.

The application is fully compiled before starting, regardless of the current setting of the Compile on Demand option on the Advanced Options Tab.  Choosing Start With Full Compile does not alter the Compile on Demand setting.

Use Start With Full Compile to start OLE server projects.  Starting an OLE server project with the Start Command when Compile on Demand checked may result in compile-time errors being detected after you have test applications running.  If correcting an error requires restarting the OLE server, your test applications may be left holding invalid object references.

This command is available only at design time.  Start With Full Compile is grayed at run time and in break mode.

Keyboard shortcut: CTRL+F5.


Start Command (Run Menu) See Also
See Also

Advanced Options Tab

Break Command (Run Menu)

Creating an OLE Server

Creating Your Own Objects

End Command (Run Menu)

Project Options Tab

Restart Command (Run Menu)

Start Command (Run Menu)


Using the DBGrid Control

See Also

When initially created, the DBGrid (Apex data-bound grid) control has a single column and a single row.  Using the Properties window, you can change any of the visible attributes.

When you set the DataSource property, the DBGrid control accesses the Recordset created by the Data control and sets the number of columns and the following properties:

Column property	Set from Field object property

Caption	Name

ColIndex 	OrdinalPosition

DefaultValue	DefaultValue

DBGrid columns are ordered (both visually and in the Columns collection) according to the OrdinalPosition property of the Field objects in the underlying Recordset object.  If desired, you can use the Retrieve Fields option to initialize the DBGrid columns to match the names and fields of the current Recordset.

Pop-Up Menu

You can make the DBGrid control UI-active by choosing Edit from the control's pop-up menu, which can be selected with the right mouse button.  Before the DBGrid control is UI-active, the Properties window displays the properties for the DBGrid control as a whole and the control can be moved and sized.

Once the DBGrid control is UI-active, you can select one or more columns by clicking the column heading or, to select a range of columns, by clicking and dragging over the column headings or pressing SHIFT and clicking the column headings.  After you select the columns, you can move or size the columns or use the custom control properties dialog box to alter Column object properties.

A pop-up menu can be used to add or delete columns, or to cut and paste columns to and from the Clipboard.

If you click outside the DBGrid control, it is no longer UI-active.

Custom Properties Dialog Box

When you select Custom in the Properties window, you access the Apex Data Bound Grid Control Properties dialog box.  You can use this dialog box to interactively set properties for the DBGrid control as a whole or for individually selected columns.  The following tabs are available for the DBGrid control:

Tab	Description

General	Shows properties that apply to the entire DBGrid control and can be assessed at design time.  These properties are also available in the standard Properties window.

Columns	Shows properties for an individual column.  If multiple columns are selected, the leftmost column in the Columns tab is affected.  This is the only way to set many of the column properties.  Setting Column object properties doesn't affect overall DBGrid control properties.

Colors	Allows selection of overall DBGrid control colors.  Column object colors aren't affected by these settings.

Fonts	Allows selection of overall DBGrid control and heading fonts.  Column object fonts aren't affected by these settings.

Run Time Appearance and Operation

The DBGrid control displays records from the underlying Recordset object at run time.  As long as there are records in the Recordset, there is always a single current record in the DBGrid control, even if multiple rows in the control are selected.  Although more than one column may be selected, there is only one current column.

You can set the current record  by using the DBGrid control's Bookmark property.  Use the ColIndex property to set the current column.  If you set the MultiSelect property to True, the selected columns can be accessed using the SelBookmarks collection returned in the SelBookmarks property.  If the RecordSelectors property is True, the user can select an entire row by clicking the record selector icon for that row.

Within a single row, individual cells can be selected and the selection can be extended to include any number of contiguous cells in the same row or in adjoining rows.  You can set the horizontal bounds of the selection in the SelStartCol and SelEndCol properties.  If the user clicks on a column header, the HeadClick event is generated, but the column selection isn't affected.

If the Column object's AllowSizing property and the DBGrid object's RecordSelectors property are both True, the user can drag the border between rows to resize the row height.  If the DBGrid object's HeadLines property is greater than or equal to 1 and the Column object AllowSizing property is True for a chosen Column object, the user can drag the column border to resize the column width.

Unbound Features

When the DataMode property of the DBGrid is set to 1, or unbound mode, the control is not bound to any particular data source.  Synchronization between the data source and the data displayed in the DBGrid must be performed by your application.  The DBGrid switches from automatically managing your data to sending you notification messages through special unbound events, so that your application can manage the data instead.

For example, when you delete a row in a bound DBGrid, the data is automatically deleted from your underlying data source.  When you delete a row in an unbound DBGrid, however, your application is notified through an event (in this case, the UnboundDeleteRow event).  The event alerts your application that a row was deleted in the grid by a user, and it notifies you which row was deleted.  It is then up to your application to actually remove the row of data from the underlying data source in whatever manner you prefer.

In essence, an unbound DBGrid control serves as a front-end user interface for displaying and editing your data, while giving you complete control over how the data is managed behind the scenes.


See Also

AllowSizing Property

Bookmark Property

Caption Property

ColIndex Property

Column Object, Columns Collection

DataMode Property

DataSource Property

DBGrid Control

DefaultValue Property

HeadLines Property

MultiSelect Property

RecordSelectors Property

Recordset Object, Recordsets Collection

RowSource Property

SelBookmarks Collection

UnboundDeleteRow Event


Screen Object

See Also	Properties

Manipulates forms according to their placement on the screen and controls the mouse pointer outside your application's forms at run time.  The Screen object is accessed with the keyword Screen.

Note	 For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

Screen

Remarks

Using the Screen object, you can set the MousePointer property of the Screen object to the hourglass pointer while a modal form is displayed.


See Also

Make OLE DLL File Command


Screen Object Properties

ActiveControl Property

ActiveForm Property

FontCount Property

Fonts Property

Height Property

MouseIcon Property

MousePointer Property

TwipsPerPixelX Property

TwipsPerPixelY Property

Width Property


Refresh Method

See Also	Example	Applies To

Forces a complete repaint of a form or control.

Syntax

object.Refresh

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use the Refresh method when you want to:

Completely display one form while another form loads.

Update the contents of a file-system list box, such as a FileListBox control.

Update the data structures of a Data control.

Refresh can't be used on MDI forms, but can be used on MDI child forms.  You can't 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 directory structure, 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 property settings have changed) and rebuild the dynaset in the control's Recordset property.


 See Also

DoEvents Function

MDIChild Property

MDIForm Object

Paint Event


Refresh Method Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

HScrollBar Control

Image Control

Label Control

Line Control

ListBox Control

Menu Control

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

VScrollBar Control


Refresh Method Example

This example uses the Refresh method to update a FileListBox control as test files are created.  To try this example, paste the code into the Declarations section of a form with a FileListBox control named File1, and then run the example and click the form.

Private Sub Form_Click ()

Dim FNMA, I, Msg	' Declare variables.

File1.Pattern = "TestFile.*"	' Set file pattern.

For I = 1 To 8	' Do eight times.

FNMA = "TESTFILE." & I

Open FNMA 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


SetFocus Method

See Also	Applies To

Moves the focus to the specified control or form.

Syntax

object.SetFocus

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The object must be a Form object, MDIForm object, or control that can receive the focus.  After invoking the SetFocus method, any user input is directed to the specified form or control.

You can only move the focus to a visible form or control.  Because a form and controls on a form aren't visible until the form's Load event has finished, you can't use the SetFocus method to move the focus to the form being loaded in its own Load event unless you first use the Show method to show the form before the Form_Load event procedure is finished.

You also can't move 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 receive the focus using the SetFocus method.


 See Also

Enabled Property

Load Statement

Show Method


SetFocus Method Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

HScrollBar Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control

VScrollBar Control


DblClick Event

See Also	Example	Applies To

Occurs when the user presses and releases a mouse button and then presses and releases 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 ComboBox control whose Style property is set to 1 (Simple) or in a FileListBox, ListBox, DBCombo, or DBList control.

Syntax

Private Sub Form_DblClick ( )

Private Sub object_DblClick (index As Integer)

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	Identifies the control if it's in a control array.

Remarks

The argument Index uniquely identifies a control if it's 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.  You can also use this type of procedure to carry 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 event procedure for a list box or file list box in tandem with a default button [image] a CommandButton control with its Default property set to True.  As part of the DblClick event procedure for the list box, you simply call the default button's Click event.

For those objects that receive Mouse events, the events occur in this order: MouseDown, MouseUp, Click, DblClick, and MouseUp.

If DblClick doesn't 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 in the Control Panel.  When you're attaching procedures for these related events, be sure that their actions don't conflict.  Controls that don't 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

Click Event

MouseDown, MouseUp Events


DblClick Event Example

This example displays a selected list item in a TextBox control when either a CommandButton control is clicked or a list item is double-clicked.  To try this example, paste the code into the Declarations section of a Form object that contains a ListBox control, a TextBox control, and a CommandButton control.  Then run the example and click the CommandButton control or double-click an item in the ListBox control.

Private Sub Form_Load ()

List1.AddItem "John"	' Add list box entries.

List1.AddItem "Paul"

List1.AddItem "George"

List1.AddItem "Ringo"

End Sub

Private Sub List1_DblClick ()

Command1.Value = True	' Trigger Click event.

End Sub

Private Sub Command1_Click ()

Text1.Text = List1.Text	' Display selection.

End Sub


DblClick Event Applies To

ComboBox Control

DBCombo Control

DBGrid Control

DBList Control

FileListBox Control

Form Object

Frame Control

Grid Control

Image Control

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


HelpFile Property (App, CommonDialog, MenuLine)

See Also	Example	Applies To

Specifies the path and filename of a Microsoft Windows Help file used by your application to display Help or online documentation.

Syntax

object.HelpFile[ = filename]

The HelpFile property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filename	A string expression specifying the path and filename of the Windows Help file for your application.

Remarks

If you've created a 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.

You can also use the HelpFile property to determine what Help file is displayed when a user requests Help from the Object Browser for an OLE server.

Note   Building a Help file requires the Microsoft Windows Help Compiler, which is available with Visual Basic, Professional Edition.


See Also

HelpContextID Property


HelpFile Property Example

This 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 object that contains a TextBox control and a Frame control with an OptionButton control inside of it.  Run the example.  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

Private Sub Form_Load ()

App.HelpFile = "VB.HLP"

Frame1.HelpContextID = winColorPalette

Text1.HelpContextID = winToolbox

Form1.HelpContextID = winCodeWindow

End Sub


HelpFile Property Applies To

App Object

CommonDialog Control

MenuLine Object (Add-In)


Clipboard Object

Methods

Provides access to the system Clipboard.

Syntax

Clipboard

Remarks

The Clipboard object 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.

The Clipboard object 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 graphic.  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.


Clipboard Object Methods

Clear Method

GetData Method

GetFormat Method

GetText Method

SetData Method

SetText Method


Printer Object, Printers Collection

See Also	Properties	Methods

The Printer object enables you to communicate with a system printer (initially the default system printer).

The Printers collection enables you to gather information about all the available printers on the system.

Note	 For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

Printer

Printers(index)

The index placeholder represents an integer with a range from 0 to Printers.Count-1.

Remarks

Use graphics methods to draw text and graphics on the Printer object.  Once the Printer object contains the output you want to print, you can use the EndDoc method to send the output directly to the default printer for the application.

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.

The Printers collection enables you to query the available printers so you can specify a default printer for your application.  For example, you may want to find out which of the available printers uses a specific printer driver.  The following code checks all the available printers for the first printer with its page orientation set to portrait:

Dim X As Printer

For Each X In Printers

If X.Orientation = vbPRORPortrait Then

' Set printer as system default.

Set Printer = X

' Stop looking for a printer.

Exit For

End If

Next

You designate one of the printers in the Printers collection as the default printer by using the Set statement.  The preceding example designates the printer identified by the object variable X, the default printer for the application.

Note   If you use the Printers collection to specify a particular printer, as in Printers(3), you can only access properties on a read-only basis.  To both read and write the properties of an individual printer, you must first make that printer the default printer for the application.


 See Also

Make OLE DLL File Command

Set Statement


Printer Object, Printers Collection Properties

Legend

ColorMode Property

Copies Property

Count Property

CurrentX, CurrentY Properties

DeviceName Property

DrawMode Property

DrawStyle Property

DrawWidth Property

DriverName Property

Duplex Property

FillColor Property

FillStyle Property

Font Property

FontBold Property

FontCount Property

FontItalic Property

FontName Property

Fonts Property

FontSize Property

FontStrikethru Property

FontTransparent Property

FontUnderline Property

ForeColor Property

hDC Property

Height Property

Orientation Property

Page Property

PaperBin Property

PaperSize Property

Port Property

PrintQuality Property

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleTop Property

ScaleWidth Property

TrackDefault Property

TwipsPerPixelX, TwipsPerPixelY Properties

Width Property

Zoom Property


Printer Object, Printers Collection Methods

Legend

Circle Method

EndDoc Method

KillDoc Method

Line Method

NewPage Method

PaintPicture Method

Print Method

PSet Method

Scale Method

ScaleX, ScaleY Methods

TextHeight Method

TextWidth Method


Font Object

See Also	Properties

The Font object contains information needed to format text for display in the interface of an application or for printed output.

Syntax

Font

Remarks

You frequently identify a Font object using the Font property of an object that displays text (such as a Form object or the Printer object).

You cannot create a Font object using code like Dim X As New Font.  If you want to create a Font object, you must use the StdFont object like this:

Dim X As New StdFont

If you put a TextBox control named Text1 on a form, you can set one Font object equal to another using the Set statement, as in the following example:

Dim X As New StdFont

X.Bold = True

X.Name = "Arial"

Set Text1.Font = X


See Also

Font Property

Fonts Property

Set Statement


Font Object Properties

Bold Property

Italic Property

Name Property

Size Property

StrikeThrough Property

Underline Property

Weight Property


Load Statement

See Also	Example

Loads a form or control into memory.

Syntax

Load object

The object placeholder is the name of a Form object, MDIForm object, or control array element to load.

Remarks

You don't need 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's not already loaded.  For example, the Show method loads a form before displaying it.  Once the form is loaded, its properties and controls can be altered by the application, 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're 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 object, it sets form properties to their initial values and then performs the Load event procedure.  When an application starts, Visual Basic automatically loads and displays the application's startup form.

If you load a Form with the MDIChild property set to True before loading the MDIForm, the MDIForm is automatically loaded before the child form.  Loading an MDI child form causes it to be visible immediately after the Form_Load event procedure ends because MDI child forms can't 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

This example uses the Load statement to load a Form object.  To try this example, paste the code into the Declarations section of a Form object, and then run the example and click the Form object.

Private 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


Unload Statement

See Also	Example

Unloads a form or control from memory.

Syntax

Unload object

The object placeholder is the name of a Form object or control array element to unload.

Remarks

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 values.

Before a form is unloaded, the Query_Unload event procedure occurs, followed by the Form_Unload event procedure.  Setting the cancel argument to True in either of these events keeps the form from being unloaded.  For MDIForm objects, the MDIForm object's Query_Unload event procedure occurs, followed by the Query_Unload event procedure and Form_Unload event procedure for each MDI child form, and finally the MDIForm object's Form_Unload event procedure.

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; however, 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   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

This example uses the Unload statement to unload a Form object.  To try this example, paste the code into the Declarations section of a Form object, and then run the example and click the Form object.

Private 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 graphic into a Form object, PictureBox control, or Image control.

Syntax

LoadPicture([stringexpression])

The stringexpression argument is the name of a graphics file to be loaded.

Remarks

Graphics are cleared from forms, picture boxes, and image controls by assigning LoadPicture with no argument.

Graphics formats recognized by Visual Basic include bitmap (.BMP) files, icon (.ICO) files, run-length encoded (.RLE) files, and metafile (.WMF) files.

To load graphics for display in a PictureBox control, 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 assign an icon to a form, set the return value of the LoadPicture function to the Icon property of the Form object:

Form1.Icon = LoadPicture("MYICON.ICO")

Icons can also be assigned to the DragIcon property of all controls except Timer controls and Menu controls.  For example:

Command1.DragIcon = LoadPicture("MYICON.ICO")

Load a graphics file into the system 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

This example uses the LoadPicture function to load a picture into a Form object and to clear the picture from the Form object.  To try this example, paste the code into the Declarations section of a Form object, and then run the example and click the Form object.

Private 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 = "Couldn't 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


SavePicture Statement

See Also	Example

Saves a graphic from a Form object, PictureBox control, or Image control to a file.

Syntax

SavePicture picture, stringexpression

The SavePicture statement syntax has these parts:

Part	Description

picture	Picture or Image property from which the graphics file is to be created.

stringexpression	Filename of the graphics file to save.

Remarks

If a graphic was loaded from file to the Picture property, either at design time or at run time, it's saved using the same format as the original file.  Graphics from the Image property are always saved as bitmap (.BMP) files.


See Also

Image Property

LoadPicture Function

Picture Property


SavePicture Statement Example

This example uses the SavePicture statement to save a graphic drawn on a Form object.  To try this example, paste the code into the Declarations section of a Form object, and then run the example and click the Form object.

Private 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


You need to fill in the RecordSource property of the Data control to get a list of field names.

Before you can see a list of possible settings for the DataField property of a bound control, you must first set the RecordSource property of the Data control.


You need to fill in the DatabaseName and/or Connect properties to get a list of recordsources.

Before you can see a list of possible settings for the RecordSource property of the Data control, you must first set at least the DatabaseName property (for Access database .MDB files), and possibly the Connect property (for all non-Access database files).


Can't empty Clipboard

The Clipboard was opened but could not be emptied.


Can't open Clipboard

The Clipboard has already been opened by another application.


Line 'item1': 'item2' has a quoted string where the property name should be.

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'.

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.

You attempted to load a control into a control which isn't a valid container.


Line 'item1': Cannot load control 'item2'; name already in use.

The control named in the ASCII text file couldn't 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.

A top-level Menu control appeared in the ASCII form file with its Checked property set to True.  Top-level menus can't be checked.  The Menu control will be loaded, but its Checked property won't be set.


Line 'item1': Cannot set Shortcut property in menu 'item2'.  Parent menu cannot have a shortcut key.

A top-level Menu control appeared in the ASCII form file with a shortcut key defined.  Top-level menus can't have a shortcut key.  The Menu control will be loaded, but its Shortcut property won't be set.


Line 'item1': Class 'item2' of control 'item3' was not a loaded control class.

The ASCII file contains a control class that Visual Basic doesn't recognize.  Add the custom control with this class to your project.


Line 'item1': Class name too long; truncated to 'item2'.

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'.

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.

The control can't 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'.

The ASCII file contains controls nested more than seven levels deep.


Line 'item1': Missing or invalid control class in file 'item2'.

The ASCII file contains an unknown control class in the form description, or the class name isn't a valid string in Visual Basic.


Line 'item1': Missing or invalid control name in file 'item2'.

The ASCII file contains an unknown control name in the form description, or the control name isn't a valid string in Visual Basic.


Line 'item1': Parent menu 'item2' cannot be loaded as a separator.

The ASCII file contains a Menu control whose parent or top-level menu is defined as a menu separator.  Top-level menus can't be menu separators.  The separator won't be set.


Line 'item1': Property 'item2' in 'item3' could not be loaded.

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.

Visual Basic can't 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.

The ASCII file contains a reference to a file that Visual Basic couldn't find in the specified directory.


Line 'item1': Property 'item2' in 'item3' had an invalid value.

The ASCII file contains a property with a value that isn't correct for this control.  The property is set with its default value.


Line 'item1': Property 'item2' in 'item3' must be a quoted string.

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.

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 '='.
Line 'item1': Syntax error: property 'item2' in 'item3' was missing an '='.

The ASCII file contains a property name and value without an equal sign between them.  The property isn't loaded.


Line 'item1': The control name 'item2' is invalid.

The ASCII file contains a control name that isn't a valid string in Visual Basic.  The control isn't loaded.


Line 'item1': The Form or MDIForm name 'item2' is already in use; cannot load this form.

The ASCII file contains a form with a name that is already being used elsewhere in the application.  The form isn't loaded.


Line 'item1': The Form or MDIForm name 'item2' is not valid; cannot load this form.

The ASCII file contains a form name that isn't a valid string in Visual Basic.  The form isn't loaded.


Line 'item1': The name 'item2' is already in use as a 'item3' name.
Line 'item1': The name 'item2' is already in use as an 'item3' name.

The ASCII file contains a name that is already used elsewhere in the application.


Line 'item1': The property name 'item2' in 'item3' is invalid.

The ASCII file contains a property name that isn't a valid property for that control.


Cannot remove last non-fixed row (Error 30015)

A Grid control must contain at least one row.


Cannot use AddItem on a fixed row (Error 30001)

You can't insert a fixed row in a Grid control.  Use the FixedRows property to set the number of fixed rows in a Grid.


Cannot use RemoveItem on a fixed row (Error 30000)

See Also

You can't delete a fixed row from a Grid control.  The number of fixed rows is determined by the FixedRows property.


See Also

FixedCols, FixedRows Properties


Cols must be one more than FixedCols value (Error 30019)

See Also

There must be at least one nonfixed row and one nonfixed column.  The FixedCols or FixedRows properties can't be equal to or greater than the Cols or Rows properties, respectively.


See Also

Cols, Rows Properties

FixedCols, FixedRows Properties


FixedCols must be one less than Cols value (Error 30017)

See Also

The number of columns assigned as fixed in a Grid control (using the FixedCols property) must be one less than the number of columns.


See Also

FixedCols, FixedRows Properties


FixedRows must be one less than Rows value (Error 30016)

See Also

The number of rows assigned as fixed in a Grid control (using the FixedRows property) must be one less than the number of rows.


See Also

FixedCols, FixedRows Properties


Grid does not contain that row (Error 30002)

See Also

You tried to access a row that doesn't exist.  The first row in a Grid control is zero.  Therefore, the last row is the number of rows minus one.  Use the Rows property to set or return the number of rows in a Grid.


See Also

Cols, Rows Properties


Invalid alignment value (Error 30005)

See Also

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.


See Also

FixedAlignment Property

ColAlignment Property


Invalid column number for alignment (Error 30004)

See Also

You can't align a fixed column with the ColAlignment property; use the FixedAlignment property.  Set the index argument of the ColAlignment property to a column that isn't a fixed column.  The FixedCols property returns the number of fixed columns in a Grid.


See Also

FixedAlignment Property

ColAlignment Property

FixedCols, FixedRows Properties


Invalid column value (Error 30010)

See Also

You attempted to access a column that doesn't exist.  The first column in a Grid control is zero.  Therefore, the last column is the number of columns minus one.  Use the Cols property to set or return the number of columns in a Grid.


See Also

Cols, Rows Properties


Invalid column width value (Error 30014)

See Also

The value of the ColWidth property must be greater than or equal to one.


See Also

ColWidth Property


Invalid row height value (Error 30013)

See Also

The value of the RowHeight property must be greater than or equal to one.


See Also

RowHeight Property


Invalid row value (Error 30009)

See Also

You attempted to access a row that doesn't exist.  The first row in a Grid control is zero.  Therefore, the last row is the number of rows minus one.  Use the Rows property to set or return the number of rows in a Grid.


See Also

Cols, Rows Properties


Not a valid picture type (Error 30008)

See Also

You can't display a Windows metafile (.WMF) in a Grid control cell.  The Picture property supports only bitmaps (.BMP) and icons (.ICO).


See Also

Picture Property


Rows must be one more than FixedRows value (Error 30018)

See Also

The number of rows assigned in a Grid control (using the Rows property) must be one more than the number of fixed rows.


See Also

Cols, Rows Properties


Unable to allocate memory for grid (Error 30006)

You are getting low on memory.  Close some unused applications or documents.


Unable to register the memory manager (Error 30011)

There was insufficient memory to store the requested information in the Grid control.


No public class module detected

See Also

The project does not contain any class modules whose Public property is set to True.

Make OLE DLL compiles your project as an in process OLE server.  In order to be used by other applications, an in-process OLE server must contain at least one externally createable class; that is, a class module whose Public property is set to True, and whose Instancing property is set to Createable MultiUse.

Other applications can create objects from an externally createable class by using the New operator with the Set statement, by declaring a variable with the New keyword, or by calling the CreateObject function.


See Also

Creating an OLE Server

Make OLE DLL File

Using Externally Creatable Objects


AddItem Method

See Also	Example	Applies To

Adds an item to a ListBox or ComboBox control or adds a row to a Grid control.  Doesn't support named arguments.

Syntax

object.AddItem item, index

The AddItem method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

item	Required.  String expression specifying the item to add to the object.  For the Grid control only, use the tab character (character code 09) to separate multiple strings you want to insert into each column of a newly added row.

index	Optional.  Integer specifying the position within the object where the new item or row is placed.  For the first item in a ListBox or ComboBox control or for the first row in a Grid control, index is 0.

Remarks

If you supply a valid value for index, item is placed at that position within the object.  If index is omitted, item is added at the proper sorted position (if the Sorted property is set to True) or to the end of the list (if Sorted is set to False).

A ListBox or ComboBox control that is bound to a Data control doesn't support the AddItem method.


See Also

Clear Method

RemoveItem Method


AddItem Method Applies To

ComboBox Control

Grid Control

ListBox Control


Arrange Method

See Also	Example	Applies To

Arranges the windows or icons within an MDIForm object.  Doesn't support named arguments.

Syntax

object.Arrange arrangement

The Arrange method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

arrangement	Required.  A value or constant that specifies how to arrange windows or icons on an MDIForm object, as described in Settings.

Settings

The settings for arrangement are:

Constant	Value	Description

vbCascade	0	Cascades all nonminimized MDI child forms.

vbTileHorizontal	1	Tiles all nonminimized MDI child forms horizontally.

vbTileVertical	2	Tiles all nonminimized MDI child forms vertically.

vbArrangeIcons	3	Arranges icons for minimized MDI child forms.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Windows or icons are arranged even if the MDIForm object is minimized.  Results are visible when the MDIForm is maximized.


See Also

ZOrder Method


Arrange Method Applies To

MDIForm Object


Clear Method (Clipboard, ComboBox, ListBox)

See Also	Example	Applies To

Clears the contents of a ListBox, ComboBox, or the system Clipboard.

Syntax

object.Clear

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

A ListBox or ComboBox control bound to a Data control doesn't support the Clear method.


See Also

AddItem Method

RemoveItem Method


Clear Method Applies To

Clipboard Object

ComboBox Control

ListBox Control


Cls Method

See Also	Example	Applies To

Clears graphics and text generated at run time from a Form or PictureBox.

Syntax

object.Cls

The object placeholder represents an object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form with the focus is assumed to be object.

Remarks

Cls clears text and graphics generated at run time by graphics and printing statements.  Background bitmaps set using the Picture property and controls placed on a Form at design time aren't affected by Cls.  Graphics and text placed on a Form or PictureBox while the AutoRedraw property is set to True aren't affected if AutoRedraw is set to False before Cls is invoked.  That is, you can maintain text and graphics on a Form or PictureBox by manipulating the AutoRedraw property of the object you're working with.

After Cls is invoked, the CurrentX and CurrentY properties of object are reset to 0.


See Also

AutoRedraw Property

CurrentX, CurrentY Properties


Cls Method Applies To

Form Object

PictureBox Control


Drag Method

See Also	Example	Applies To

Begins, ends, or cancels a drag operation of any control except the Line, Menu, Shape, Timer, or CommonDialog controls.  Doesn't support named arguments.

Syntax

object.Drag action

The Drag method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the object whose event procedure contains the Drag method is assumed.

action	Optional.  A constant or value that specifies the action to perform, as described in Settings.  If action is omitted, the default is to begin dragging the object.

Settings

The settings for action are:

Constant	Value	Description

vbCancel	0	Cancels drag operation.

vbBeginDrag	1	Begins dragging object.

vbEndDrag	2	Ends dragging and drop object.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Using the Drag method to control a drag-and-drop operation is required only when the DragMode property of the object is set to Manual (0).  However, you can use Drag on an object whose DragMode property is set to Automatic (1 or vbAutomatic).

If you want the mouse pointer to change shape while the object is being dragged, use either the DragIcon or MousePointer property.  The MousePointer property is only used if no DragIcon is specified.

In earlier versions of Visual Basic, Drag was an asynchronous method where subsequent statements were invoked even though the Drag action wasn't finished.  In Visual Basic version 4.0, Drag is a synchronous method in which subsequent statements aren't invoked until the Drag action is finished.


See Also

DragDrop Event

DragIcon Property

DragMode Property

DragOver Event

MousePointer Property


Drag Method Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBGrid Control

DirListBox Control

DriveListBox Control

FileListBox Control

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control

VScrollBar Control


EndDoc Method

See Also	Example	Applies To

Terminates a print operation sent to the Printer object, releasing the document to the print device or spooler.

Syntax

object.EndDoc

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

If EndDoc is invoked immediately after the NewPage method, no additional blank page is printed.


See Also

KillDoc Method

NewPage Method


EndDoc Method Applies To

Printer Object


GetData Method

See Also	Example	Applies To

Returns a graphic from the Clipboard object.  Doesn't support named arguments.

Syntax

object.GetData (format)

The GetData method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

format 	Optional.  A constant or value that specifies the Clipboard graphics format, as described in Settings.  Parentheses must enclose the constant or value.  If format is 0 or omitted, GetData automatically uses the appropriate format.

Settings

The settings for format are:

Constant	Value	Description

vbCFBitmap	2	Bitmap (.BMP files)

vbCFMetafile	3	Metafile (.WMF files)

vbCFDIB	8	Device-independent bitmap (DIB)

vbCFPalette	9	Color palette

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

If no graphic on the Clipboard object matches the expected format, nothing is returned.  If only a color palette is present on the Clipboard object, a minimum size (1 x 1) DIB is created.


See Also

GetFormat Method

GetText Method

SetData Method

SetText Method


GetData Method Applies To

Clipboard Object


GetFormat Method

See Also	Example	Applies To

Returns an integer indicating whether an item on the Clipboard object matches a specified format.  Doesn't support named arguments.

Syntax

object.GetFormat (format)

The GetFormat method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

format 	Required.  A value or constant that specifies the Clipboard object format, as described in Settings.  Parentheses must enclose the constant or value.

Settings

The settings for format are:

Constant	Value	Description

vbCFLink	HBF00	DDE conversation information

vbCFText	1	Text

vbCFBitmap	2	Bitmap (.BMP files)

vbCFMetafile	3	Metafile (.WMF files)

vbCFDIB	8	Device-independent bitmap (DIB)

vbCFPalette	9	Color palette

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

The GetFormat method returns True if an item on the Clipboard object matches the specified format.  Otherwise, it returns False.

For vbCFDIB and vbCFBitmap formats, whatever color palette is on the Clipboard is used when the graphic is displayed.


See Also

GetData Method

GetText Method

SetData Method

SetText Method


GetFormat Method Applies To

Clipboard Object


GetText Method

See Also	Example	Applies To

Returns a text string from the Clipboard object.  Doesn't support named arguments.

Syntax

object.GetText (format)

The GetText method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

format 	Optional.  A value or constant that specifies the Clipboard object format, as described in Settings.  Parentheses must enclose the constant or value.

Settings

The settings for format are:

Constant	Value	Description

vbCFLink	&HBF00	DDE conversation information

vbCFText	1	(Default) Text

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

If no text string on the Clipboard object matches the expected format, a zero-length string ("") is returned.


See Also

GetData Method

GetFormat Method

SetData Method

SetText Method


GetText Method Applies To

Clipboard Object


Hide Method

See Also	Example	Applies To

Hides an MDIForm or Form object but doesn't unload it.

Syntax

object.Hide

The object placeholder represents an object expression that evaluates to an object in the Applies To list.  If object is omitted, the form with the focus is assumed to be object.

Remarks

When a form is hidden, it's removed from the screen and its Visible property is set to False.  A hidden form's controls aren't accessible to the user, but they are available to the running Visual Basic application, to other processes that may be communicating with the application through DDE, and to Timer control events.

When a form is hidden, the user can't interact with the application until all code in the event procedure that caused the form to be hidden has finished executing.

If the form isn't loaded when the Hide method is invoked, the Hide method loads the form but doesn't display it.


See Also

Load Statement

Show Method

Unload Statement

Visible Property


Hide Method Applies To

Form Object

MDIForm Object


KillDoc Method

See Also	Example	Applies To

Immediately terminates the current print job.

Syntax

object.KillDoc

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

If the operating system's Print Manager is handling the print job (the Print Manager is running and has background printing enabled), KillDoc deletes the current print job and the printer receives nothing.

If Print Manager isn't handling the print job (background printing isn't enabled), some or all of the data may be sent to the printer before KillDoc can take effect.  In this case, the printer driver resets the printer when possible and terminates the print job.


See Also

EndDoc Method


KillDoc Method Applies To

Printer Object


LinkExecute Method

See Also	Example	Applies To

Sends a command string to the source application in a DDE conversation.  Doesn't support named arguments.

Syntax

object.LinkExecute string

The LinkExecute method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

string	Required.  String expression containing a command recognized by the source application.

Remarks

The actual value of string varies depending on the source application.  For example, Microsoft Excel and Microsoft Word for Windows accept command strings that consist of their macro commands enclosed in square brackets ([ ]).  To see command strings that a source application accepts, consult documentation for that application.


See Also

LinkExecute Event

LinkPoke Method

LinkRequest Method

LinkSend Method


LinkExecute Method Applies To

Label Control

PictureBox Control

TextBox Control


LinkPoke Method

See Also	Example	Applies To

Transfers the contents of a Label, PictureBox, or TextBox control to the source application in a DDE conversation.

Syntax

object.LinkPoke

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The object is the name of a Label, PictureBox, or TextBox involved in a DDE conversation as a destination.  If object is a Label, LinkPoke transfers the contents of the Caption property to the source.  If object is a PictureBox, LinkPoke transfers the contents of the Picture property to the source.  If object is a TextBox, LinkPoke transfers the contents of the Text property to the source.

Typically, information in a DDE conversation flows from source to destination.  However, LinkPoke allows a destination object to supply data to the source.  Not all source applications accept information supplied this way; if the source application doesn't accept the data, an error occurs.


See Also

LinkExecute Method

LinkRequest Method

LinkSend Method


LinkPoke Method Applies To

Label Control

PictureBox Control

TextBox Control


LinkRequest Method

See Also	Example	Applies To

Asks the source application in a DDE conversation to update the contents of a Label, PictureBox, or TextBox control.

Syntax

object.LinkRequest

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The object is the name of a Label, PictureBox, or TextBox involved in a DDE conversation as a destination.  LinkRequest causes the source application to send the most current data to object, updating the Caption property setting if object is a Label, the Picture property setting if object is a PictureBox, or the Text property setting if object is a TextBox.

If the LinkMode property of object is set to Automatic (1 or vbLinkAutomatic), the source application automatically updates object and LinkRequest isn't needed.  If the LinkMode property of object is set to Manual (2 or vbLinkManual), the source application updates object only when LinkRequest is used.  If the LinkMode property of object is set to Notify (3 or vbLinkNotify), the source notifies the destination that data has changed by invoking the LinkNotify event.  The destination must then use LinkRequest to update the data.


See Also

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkPoke Method

LinkSend Method


LinkRequest Method Applies To

Label Control

PictureBox Control

TextBox Control


LinkSend Method

See Also	Applies To

Transfers the contents of a PictureBox control to the destination application in a DDE conversation.

Syntax

object.LinkSend

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The object must be a PictureBox on a Form object that is 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 a TextBox or a Label on the Form change.  However, Visual Basic doesn't automatically notify a DDE destination application when the Picture property setting of a PictureBox on a source Form changes.  Because the amount of data in a graphic can be very large and because it seldom makes sense to update a destination application as each pixel in the picture changes, Visual Basic requires that you use the LinkSend method to explicitly notify DDE destination applications when the contents of a PictureBox changes.


See Also

LinkExecute Method

LinkPoke Method

LinkRequest Method

Picture Property


LinkSend Method Applies To

PictureBox Control


LoadResData Function

See Also

Loads data of several possible types from a resource (.RES) file and returns a Byte array.

Syntax

LoadResData(index, format)

The LoadResData function syntax has these parts:

Part	Description

index	Required.  Integer or string specifying the identifier (ID) of the data in the resource file. The resource whose ID is 1 is reserved for the application icon.

format	Required.  Value that specifies the original format of the data being returned, as described in Settings.  Value can also be the string name of a user-defined resource.

Settings

The settings for format are:

Setting	Description

1	Cursor resource

2	Bitmap resource

3	Icon resource

4	Menu resource

5	Dialog box

6	String resource

7	Font directory resource

8	Font resource

9	Accelerator table

10	User-defined resource

12	Group cursor

14	Group icon

Remarks

The data that LoadResData loads from the resource file can be up to 64K.

Using LoadResData with a bitmap, icon, or cursor resource type returns a string containing the actual bits in the resource.  If you want to use the actual bitmap, icon, or resource, use the LoadResPicture function.

Using LoadResData is useful for localizing a Visual Basic application because the resources that need to be translated are isolated in one resource file and there is no need to access the source code or recompile the application.


See Also

LoadResPicture Function

LoadResString Function

Using Resource Files


LoadResPicture Function

See Also

Loads a bitmap, icon, or cursor from a resource (.RES) file.

Syntax

LoadResPicture(index, format)

The LoadResPicture function syntax has these parts:

Part	Description

index	Required.  Integer or string specifying the identifier (ID) of the data in the resource file.  The resource whose ID is 1 is reserved for the application icon.

format	Required.  Value or constant that specifies the format of the data being returned, as described in Settings.

Settings

The settings for format are:

Constant	Value	Description

vbResBitmap	0	Bitmap resource

vbResIcon	1	Icon resource

vbResCursor	2	Cursor resource

Remarks

You can use the LoadResPicture function instead of referring to graphics stored in the Picture property of a Form or controls.

Storing bitmaps, icons, or cursors in and accessing them from resource files improves load time because you can load them individually as needed from the resource file, rather than all at once when a Form is loaded.

Using LoadResPicture is useful for localizing a Visual Basic application because the resources that need to be translated are isolated in one resource file and there is no need to access the source code or recompile the application.


See Also

LoadResData Function

LoadResString Function

Using Resource Files


LoadResString Function

See Also

Loads a string from a resource (.RES) file.

Syntax

LoadResString(index)

The LoadResString function syntax has these parts:

Part	Description

index	Required.  Integer specifying the identifier (ID) of the data in the resource file.  The resource whose ID is 1 is reserved for the application icon.

Remarks

You can use the LoadResString function instead of string literals in your code.  Storing long strings of data in and accessing them from resource files improves load time because you can load them individually as needed from the resource file, rather than all at once when a form is loaded.

Using LoadResString is useful for localizing a Visual Basic application because the resources that need to be translated are isolated in one resource file and there is no need to access the source code or recompile the application.


See Also

LoadResData Function

LoadResPicture Function

Using Resource Files


Move Method

See Also	Example	Applies To

Moves an MDIForm, Form, or control.  Doesn't support named arguments.

Syntax

object.Move left, top, width, height

The Move method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form with the focus is assumed to be object.

left	Required.  Single-precision value indicating the horizontal coordinate (x-axis) for the left edge of object.

top	Optional.  Single-precision value indicating the vertical coordinate (y-axis) for the top edge of object.

width	Optional.  Single-precision value indicating the new width of object.

height	Optional.  Single-precision value indicating the new height of object.

Remarks

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 can't specify width without specifying left and top.  Any trailing arguments that are unspecified remain unchanged.

For forms and controls in a Frame control, the coordinate system is always in twips.  Moving a form on the screen or moving a control in a Frame is always relative to the origin (0,0), which is the upper-left corner.  When moving a control on a Form object or in a PictureBox (or an MDI child form on an MDIForm object), the coordinate system of the container object is used.  The coordinate system or unit of measure is set with the ScaleMode property at design time.  You can change the coordinate system at run time with the Scale method.


See Also

Height Property

Left Property

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleWidth Property

Top Property

Width Property


Move Method Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

Line Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

VScrollBar Control


NewPage Method

See Also	Example	Applies To

Ends the current page and advances to the next page on the Printer object.

Syntax

object.NewPage

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

NewPage 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

KillDoc Method

Page Property


NewPage Method Applies To

Printer Object


PaintPicture Method

See Also	Applies To

Draws the contents of a graphics file (.BMP, .WMF, .EMF, .ICO, or .DIB) on a Form, PictureBox, or Printer.  Doesn't support named arguments.

Syntax

object.PaintPicture picture, x1, y1, width1, height1, x2, y2, width2, height2, opcode

The PaintPicture method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form object with the focus is assumed to be object.

picture	Required.  The source of the graphic to be drawn onto object.  Must be the Picture property of a Form or PictureBox.

x1, y1	Required.  Single-precision values indicating the destination coordinates (x-axis and y-axis) on object for picture to be drawn.  The ScaleMode property of object determines the unit of measure used.

width1	Optional.  Single-precision value indicating the destination width of picture.  The ScaleMode property of object determines the unit of measure used.  If the destination width is larger or smaller than the source width (width2), picture is stretched or compressed to fit.  If omitted, the source width is used.

height1	Optional.  Single-precision value indicating the destination height of picture.  The ScaleMode property of object determines the unit of measure used.  If the destination height is larger or smaller than the source height (height2), picture is stretched or compressed to fit.  If omitted, the source height is used.

x2, y2	Optional.  Single-precision values indicating the coordinates (x-axis and y-axis) of a clipping region within picture.  The ScaleMode property of object determines the unit of measure used.  If omitted, 0 is assumed.

width2	Optional.  Single-precision value indicating the source width of a clipping region within picture.  The ScaleMode property of object determines the unit of measure used.  If omitted, the entire source width is used.

height2	Optional.  Single-precision value indicating the source height of a clipping region within picture.  The ScaleMode property of object determines the unit of measure used.  If omitted, the entire source height is used.

opcode	Optional.  Long value or code that is used only with bitmaps.  It defines a bit-wise operation (for example, Not or Xor operator) that is performed on picture as it's drawn on object.  For a complete list of bit-wise operators, see the BitBlt topic in the Windows SDK Help file (WIN31WH.HLP).

Remarks

You can flip a bitmap horizontally or vertically by using negative values for the destination height (height1) and/or the destination width (width1).

You can omit as many optional trailing arguments as you want.  If you omit an optional trailing argument or arguments, don't use any commas following the last argument you specify.  If you want to specify an optional argument, you must specify all optional arguments that appear in the syntax before it.


 See Also

Scale Method

ScaleMode Property

ScaleX, ScaleY Methods


 PaintPicture Method Applies To

Form Object

PictureBox Control

Printer Object


Point Method

See Also	Example	Applies To

Returns, as a long integer, the red-green-blue (RGB) color of the specified point on a Form or PictureBox.  Doesn't support named arguments.

Syntax

object.Point(x, y)

The Point method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form object with the focus is assumed to be object.

x, y	Required.  Single-precision values indicating the horizontal (x-axis) and vertical (y-axis) coordinates of the point in the ScaleMode property of the Form or PictureBox.  Parentheses must enclose the values.

Remarks

If the point referred to by the x and y coordinates is outside object, the Point method returns -1.


See Also

Circle Method

Line Method

Print Method

PSet Method


Point Method Applies To

Form Object

PictureBox Control


PopupMenu Method

See Also	Example	Applies To

Displays a pop-up menu on an MDIForm or Form object at the current mouse location or at specified coordinates.  Doesn't support named arguments.

Syntax

object.PopupMenu menuname, flags, x, y, boldcommand

The PopupMenu method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form with the focus is assumed to be object.

menuname	Required.  The name of the pop-up menu to be displayed.  The specified menu must have at least one submenu.

flags	Optional.  A value or constant that specifies the location and behavior of a pop-up menu, as described in Settings.

x	Optional.  Specifies the x-coordinate where the pop-up menu is displayed.  If omitted, the mouse coordinate is used.

y	Optional.  Specifies the y-coordinate where the pop-up menu is displayed.  If omitted, the mouse coordinate is used.

boldcommand	Optional.  Specifies the name of a menu control in the pop-up menu to display its caption in bold text.  If omitted, no controls in the pop-up menu appear in bold.

This argument works only for applications running under Windows 95. The application will ignore this argument when running under 16-bit versions of Windows or Windows NT 3.51 and earlier.

Settings

The settings for flags are:

Constant (location)	Value	Description

vbPopupMenuLeftAlign	0	(Default) The left side of the pop-up menu is located at x.

vbPopupMenuCenterAlign	4	The pop-up menu is centered at x.

vbPopupMenuRightAlign	8	The right side of the pop-up menu is located at x.

Constant (behavior)	Value	Description

vbPopupMenuLeftButton	0	(Default) An item on the pop-up menu reacts to a mouse click only when you use the left mouse button.

vbPopupMenuRightButton	2	An item on the pop-up menu reacts to a mouse click when you use either the right or the left mouse button.

Note   The flags parameter has no effect on applications running under Microsoft Windows version 3.0 or earlier.  To specify two flags, combine one constant from each group using the Or operator.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

You specify the unit of measure for the x and y coordinates using the ScaleMode property.  The x and y coordinates define where the pop-up is displayed relative to the specified form.  If the x and y coordinates aren't included, the pop-up menu is displayed at the current location of the mouse pointer.

When you display a pop-up menu, the code following the call to the PopupMenu method isn't executed until the user either chooses a command from the menu (in which case the code for that command's Click event is executed before 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 open.

A pop-up menu that isn't visible on the menu bar because its Visible property is set to False in the Menu Editor can still be displayed because the Visible property of the specified menu is ignored when Visual Basic displays a pop-up menu.


See Also

Menu Editor

MouseDown Event

Or Operator

ScaleMode Property

Visible Property


PopupMenu Method Applies To

Form Object

MDIForm Object


PrintForm Method

See Also	Example	Applies To

Sends a bit-by-bit image of a Form object to the printer.

Syntax

object.PrintForm

The object placeholder represents an object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form with the focus is assumed to be object.

Remarks

PrintForm prints all visible objects and bitmaps of the Form object.  PrintForm also prints graphics added to a Form object or PictureBox control at run time if the AutoRedraw property is True when the graphics are drawn.

The printer used by PrintForm is determined by the operating system's Control Panel settings.


See Also

AutoRedraw Property

EndDoc Method

Print Method

Printer Object

TrackDefault Property


PrintForm Method Applies To

Form Object


RemoveItem Method

See Also	Example	Applies To

Removes an item from a ListBox or ComboBox control or a row from a Grid control.  Doesn't support named arguments.

Syntax

object.RemoveItem index

The RemoveItem method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

index	Required.  Integer representing the position within the object of the item or row to remove.  For the first item in a ListBox or ComboBox or for the first row in a Grid control, index = 0.

Remarks

A ListBox or ComboBox that is bound to a Data control doesn't support the RemoveItem method.


See Also

AddItem Method

Clear Method


RemoveItem Method Applies To

ComboBox Control

Grid Control

ListBox Control


Scale Method

See Also	Example	Applies To

Defines the coordinate system for a Form, PictureBox, or Printer.  Doesn't support named arguments.

Syntax

object.Scale (x1, y1) - (x2, y2)

The Scale method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form object with the focus is assumed to be object.

x1, y1	Optional.  Single-precision values indicating the horizontal (x-axis) and vertical (y-axis) coordinates that define the upper-left corner of object.  Parentheses must enclose the values.  If omitted, the second set of coordinates must also be omitted.

x2, y2	Optional.  Single-precision values indicating the horizontal and vertical coordinates that define the lower-right corner of object.  Parentheses must enclose the values.  If omitted, the first set of coordinates must also be omitted.

Remarks

The Scale method enables you to reset the coordinate system to any scale you choose.  Scale affects the coordinate system for both run-time graphics statements and the placement of controls.

If you use Scale with no arguments (both sets of coordinates omitted), it resets the coordinate system to twips.


See Also

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property


Scale Method Applies To

Form Object

PictureBox Control

Printer Object


ScaleX, ScaleY Methods

See Also	Applies To

Converts the value for the width or height of a Form, PictureBox, or Printer from one of the ScaleMode property's unit of measure to another.  Doesn't support named arguments.

Syntax

object.ScaleX (width, fromscale, toscale)

object.ScaleY (height, fromscale, toscale)

The ScaleX and ScaleY method syntaxes have these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form object with the focus is assumed to be object.

width	Required.  Specifies, for object, the number of units of measure to be converted.

height	Required.  Specifies, for object, the number of units of measure to be converted.

fromscale	Optional.  A constant or value specifying the coordinate system from which width or height of object is to be converted, as described in Settings.  The possible values of fromscale are the same as for the ScaleMode property, plus the new value of HiMetric.

toscale	Optional.  A constant or value specifying the coordinate system to which width or height of object is to be converted, as described in Settings.  The possible values of toscale are the same as for the ScaleMode property, plus the new value of HiMetric.

Settings

The settings for fromscale and toscale are:

Constant	Value	Description

vbUser	0	User-defined: indicates that the width or height of object is set to a custom value.

vbTwips	1	Twip (1440 twips per logical inch; 567 twips per logical centimeter).

vbPoints	2	Point (72 points per logical inch).

vbPixels	3	Pixel (smallest unit of monitor or printer resolution).

vbCharacters	4	Character (horizontal = 120 twips per unit; vertical = 240 twips per unit).

vbInches	5	Inch.

vbMillimeters	6	Millimeter.

vbCentimeters	7	Centimeter.

N/A	8	HiMetric.  If fromscale is omitted, HiMetric is assumed as the default.

Remarks

The ScaleX and ScaleY methods take a value (width or height), with its unit of measure specified by fromscale, and convert it to the corresponding value for the unit of measure specified by toscale.

You can also use ScaleX and ScaleY with the PaintPicture method.


See Also

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property


ScaleX, ScaleY Methods Apply To

Form Object

PictureBox Control

Printer Object


SetData Method

See Also	Applies To

Puts a picture on the Clipboard object using the specified graphic format.  Doesn't support named arguments.

Syntax

object.SetData data, format

The SetData method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

data	Required.  A graphic to be placed on the Clipboard object.

format 	Optional.  A constant or value that specifies one of the Clipboard object formats recognized by Visual Basic, as described in Settings.  If format is omitted, SetData automatically determines the graphic format.

Settings

The settings for format are:

Constant	Value	Description

vbCFBitmap	2	Bitmap (.BMP files)

vbCFMetafile	3	Metafile (.WMF files)

vbCFDIB	8	Device-independent bitmap (DIB)

vbCFPalette	9	Color palette

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

You set the graphic that is to be placed onto the Clipboard object with either the LoadPicture function or the Picture property of a Form, Image, or PictureBox.


See Also

GetData Method

GetFormat Method

GetText Method

SetText Method


SetData Method Applies To

Clipboard Object


SetText Method

See Also	Example	Applies To

Puts a text string on the Clipboard object using the specified Clipboard object format.  Doesn't support named arguments.

Syntax

object.SetText data, format

The SetText method syntax has these parts:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

data	Required.  String data to be placed onto the Clipboard.

format	Optional.  A constant or value that specifies one of the Clipboard formats recognized by Visual Basic, as described in Settings.

Settings

The settings for format are:

Constant	Value	Description

vbCFLink	&HBF00	DDE conversation information

vbCFRTF	&HBF01	RichText Format

vbCFText	1	(Default) Text

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.


See Also

GetData Method

GetFormat Method

GetText Method

SetData Method


SetText Method Applies To

Clipboard Object


Show Method

See Also	Example	Applies To

Displays an MDIForm or Form object.  Doesn't support named arguments.

Note	 For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

object.Show style

The Show method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form associated with the active form module is assumed to be object.

style	Optional.  Integer 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.

Remarks

If the specified form isn't loaded when the Show method is invoked, Visual Basic automatically loads it.

When Show displays a modeless form, subsequent code is executed as it's encountered.  When Show displays a modal form, no subsequent code is executed until the form is hidden or unloaded.

When Show displays a modal form, no input (keyboard or mouse click) can occur except to objects on the modal form.  The program must hide or unload a modal form (usually in response to some user action) before input to another form can occur.  An MDIForm can't be modal.

Although other forms in your application are disabled when a modal form is displayed, other applications aren't.

The startup form of an application is automatically shown after its Load event is invoked.


See Also

Activate Event

Hide Method

Load Statement

Make OLE DLL File Command

Unload Statement

Visible Property


Show Method Applies To

Form Object

MDIForm Object


ShowColor Method

See Also	Example	Applies To

Displays the CommonDialog control's Color dialog box.

Syntax

object.ShowColor

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


See Also

ShowFont Method

ShowHelp Method

ShowOpen Method

ShowPrinter Method

ShowSave Method


ShowColor Method Applies To

CommonDialog Control


ShowFont Method

See Also	Example	Applies To

Displays the CommonDialog control's Font dialog box.

Syntax

object.ShowFont

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Before you use the ShowFont method, you must set the Flags property of the CommonDialog control to one of three constants or values: cdlCFBoth or &H3, cdlCFPrinterFonts or &H2, or cdlCFScreenFonts or &H1.  If you don't set Flags, a message box is displayed advising you that "There are no fonts installed.", and a run-time error occurs.


See Also

Flags Property (Font Dialog)

ShowColor Method

ShowHelp Method

ShowOpen Method

ShowPrinter Method

ShowSave Method


ShowFont Method Applies To

CommonDialog Control


ShowHelp Method

See Also	Example	Applies To

Runs WINHELP.EXE and displays the Help file you specify.

Syntax

object.ShowHelp

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Before you use the ShowHelp method, you must set the HelpFile and HelpCommand properties of the CommonDialog control to one of their appropriate constants or values.  Otherwise, WINHELP.EXE doesn't display the Help file.


See Also

HelpCommand Property

HelpFile Property

ShowColor Method

ShowFont Method

ShowOpen Method

ShowPrinter Method

ShowSave Method


ShowHelp Method Applies To

CommonDialog Control


ShowOpen Method

See Also	Example	Applies To

Displays the CommonDialog control's Open dialog box.

Syntax

object.ShowOpen

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


See Also

ShowColor Method

ShowFont Method

ShowHelp Method

ShowPrinter Method

ShowSave Method


ShowOpen Method Applies To

CommonDialog Control


ShowPrinter Method

See Also	Example	Applies To

Displays the CommonDialog control's Printer dialog box.

Syntax

object.ShowPrinter

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


See Also

ShowColor Method

ShowFont Method

ShowHelp Method

ShowOpen Method

ShowSave Method


ShowPrinter Method Applies To

CommonDialog Control


ShowSave Method

See Also	Example	Applies To

Displays the CommonDialog control's Save As dialog box.

Syntax

object.ShowSave

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


See Also

ShowColor Method

ShowFont Method

ShowHelp Method

ShowOpen Method

ShowPrinter Method


ShowSave Method Applies To

CommonDialog Control


TextHeight Method

See Also	Example	Applies To

Returns the height of a text string as it would be printed in the current font of a Form, PictureBox, or Printer.  Doesn't support named arguments.

Syntax

object.TextHeight(string)

The TextHeight method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form object with the focus is assumed to be object.

string	Required.  A string expression that evaluates to a string for which the text height is determined.  Parentheses must enclose the string expression.

Remarks

The height is expressed in terms of the ScaleMode property setting or Scale method 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 text, so you can use the height to calculate and position multiple lines of text within object.

If string 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

ScaleMode Property

TextWidth Method


TextHeight Method Applies To

Form Object

PictureBox Control

Printer Object


TextWidth Method

See Also	Example	Applies To

Returns the width of a text string as it would be printed in the current font of a Form, PictureBox, or Printer.  Doesn't support named arguments.

Syntax

object.TextWidth(string)

The TextWidth method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form with the focus is assumed to be object.

string	Required.  A string expression that evaluates to a string for which the text height is determined.  Parentheses must surround the string expression.

Remarks

The width is expressed in terms of the ScaleMode property setting or Scale method coordinate system in effect for object.  Use TextWidth to determine the amount of horizontal space required to display the text.  If string contains embedded carriage returns, TextWidth returns the width of the longest line.


See Also

FontSize Property

Scale Method

ScaleMode Property

TextHeight Method


TextWidth Method Applies To

Form Object

PictureBox Control

Printer Object


ZOrder Method

See Also	Applies To

Places a specified MDIForm, Form, or control at the front or back of the z-order within its graphical level.  Doesn't support named arguments.

Syntax

object.ZOrder position

The ZOrder method syntax has these parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form with the focus is assumed to be object.

position 	Optional.  Integer indicating the position of object relative to other instances of the same object.  If position is 0 or omitted, object is positioned at the front of the z-order.  If position is 1, object is positioned at the back of the z-order.

Remarks

The z-order of objects can be set at design time by choosing the Bring To Front or Send To Back menu command from the Edit menu.

Within an MDIForm object, ZOrder sends MDI child forms to either the front or the back of the MDI client area, depending on the value of position.  For an MDIForm or Form object, ZOrder sends the form to either the front or the back of the screen, depending on the value of position.  As a result, forms can be displayed in front of or behind other running applications.

Three graphical layers are associated with forms and containers.  The back layer is the drawing space where the results of the graphics methods are displayed.  Next is the middle layer where graphical objects and Label controls are displayed.  The front layer is where all nongraphical controls like CommandButton, CheckBox, or ListBox are displayed.  Anything contained in a layer closer to the front covers anything contained in the layer(s) behind it.  ZOrder arranges objects only within the layer where the object is displayed.


See Also

Arrange Method


ZOrder Method Applies To

App Object

CheckBox Control

ComboBox Control

CommandButton Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

Line Control

ListBox Control

MDIForm Object

OptionButton Control

PictureBox Control

Screen Object

Shape Control

TextBox Control

VScrollBar Control


AddItem Method Example

This example uses the AddItem method to add 100 items to a list box.  To try this example, paste the code into the Declarations section of a form with a ListBox control named List1, and then press F5 and click the form.

Private 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


Arrange Method Example

This 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, with its MDIChild property set to True) and a picture box on the MDI Form (named Picture1).  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

Private 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

Private 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 MDI form 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


Clear Method Example

This 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 ListBox control named List1, and then press F5 and click the form.

Private 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

This example uses the Clear method to clear the Clipboard object.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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 = "Can't 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."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture.

End Sub


Cls Method Example

This example uses the Cls method to delete printed information from a form.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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 Example

This example uses the Drag method to drag the filename of a bitmap (.BMP) 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 DriveListBox, DirListBox, FileListBox, PictureBox, and Label controls.  Use the default names for all of the controls.  Size and position all controls so they can be easily seen and used.  The size and position of the label is unimportant because it's changed at run time.  When the program begins, you can browse your file system and load any bitmaps.  Once you've located a bitmap that you want to display, click the filename of that bitmap, and drag it to the picture box.

Private 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

Private Sub Dir1_Change ()	' Any change in Dir1

File1.Path = Dir1.Path	' is reflected in File1.

End Sub

Private Sub Drive1_Change ()	' Any change in Drive1

Dir1.Path = Drive1.Drive	' is reflected in Dir1.

End Sub

Private 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

Private Sub Dir1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

' Change pointer to no drop.

If State = 0 Then Source.MousePointer = 12

' Use default mouse pointer.

If State = 1 Then Source.MousePointer = 0

End Sub

Private Sub Drive1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

' Change pointer to no drop.

If State = 0 Then Source.MousePointer = 12

' Use default mouse pointer.

If State = 1 Then Source.MousePointer = 0

End Sub

Private Sub Form_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

' Change pointer to no drop.

If State = 0 Then Source.MousePointer = 12

' Use default mouse pointer.

If State = 1 Then Source.MousePointer = 0

End Sub

Private 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 can't be loaded."

ElseIf State = 1 Then

Label1.DragIcon = LoadPicture ()	' Use no drag icon.

End If

End Sub

Private 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 can't be loaded."

End Sub


EndDoc Method Example

This 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, and then press F5 and click the form.

Private 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	' Printing is finished.

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


GetData Method Example

This example uses the GetData method to copy a bitmap from the Clipboard object to a form.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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 = "Can't 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 form."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear form.

End Sub


GetFormat Method Example

This example uses the GetFormat method to determine the format of the data on the Clipboard object.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private Sub Form_Click ()

' Define bitmap formats.

Dim ClpFmt, Msg	' Declare variables.

On Error Resume Next	' Set up error handling.

If Clipboard.GetFormat(vbCFText) Then ClpFmt = ClpFmt + 1

If Clipboard.GetFormat(vbCFBitmap) Then ClpFmt = ClpFmt + 2

If Clipboard.GetFormat(vbCFDIB) 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 Example

This example uses the GetText method to copy a text string from the Clipboard object to a string variable.  To try this example, paste the code into the Declarations section of a form with a TextBox control named Text1, and then press F5 and click the form.

Private Sub Form_Click ()

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(vbCFText) 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(vbCFText)	' 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 Example

This 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, and then press F5 and click the form.

Private 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


KillDoc Method Example

This example uses the KillDoc method to terminate the current print job.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private Sub Form_Click()

For i = 1 To 40

Printer.CurrentX = 1440	' Set left margin.

Printer.CurrentY = (i * 300)	' Advance page to next line.

Printer.Print "This is line" & Str$(i) & " of text."

On Error Resume Next	' Catch any printer error.

If i = 26 Then

Printer.KillDoc	' Terminate print job abruptly.

Printer.EndDoc

End

End If

Next i

End Sub


LinkExecute Method Example

This 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 on your computer and in the path statement of your AUTOEXEC.BAT file.  Paste the code into the Declarations section of a form that has a TextBox control with the default name Text1, and then press F5 and click the form.

Private Sub Form_Click ()

Dim Cmd, I, Q, Row, Z	' Declare variables.

Q = Chr(34)	' Define quotation marks.

' Create a string containing Microsoft 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 = vbNone Then

Z = Shell("Excel", 4)	' Start Microsoft Excel.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = vbLinkManual	' 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

On Error Resume Next

Text1.LinkExecute Cmd	' Carry out Microsoft Excel commands.

MsgBox "LinkExecute DDE demo with Microsoft Excel finished.", 64

   End

End Sub


LinkPoke Method Example

This 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 the path statement of your AUTOEXEC.BAT file.  Paste the code into the Declarations section of a form that has a TextBox control with the default name Text1, and then press F5 and click the form.

Private Sub Form_Click ()

Dim Cmd, I, Q, Row, Z	' Declare variables.

Q = Chr(34)	' Define quotation marks.

' Create a string containing Microsoft 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 = vbNone Then

Z = Shell("Excel", 4)	' Start Microsoft Excel.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = vbLinkManual	' 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	' Carry out Microsoft Excel commands.

On Error Resume Next

MsgBox "LinkPoke DDE demo with Microsoft Excel finished.", 64

   End

End Sub


LinkRequest Method Example

This 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 (SHEET1.XLS).  Paste the code into the Declarations section of a form that has a TextBox control called Text1, and then press F5 and click the form.

Private Sub Form_Click ()

If Text1.LinkMode = vbNone Then	' Test link mode.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = vbLinkManual	' 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


Move Method Example

This 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, and then press F5 and click the form.

Private Sub Form_Click ()

Dim Inch, Msg	' Declare variables.

Msg = "Choose OK to resize and move this form by "

Msg = Msg & "changing the value of properties."

MsgBox Msg	' Display message.

Inch = 1440	' Set inch in twips.

Width = 4 * Inch	' Set width.

Height = 2 * Inch	' 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 * Inch, Screen.Height - Inch, 2 * Inch, Inch

End Sub


NewPage Method Example

This 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, and then press F5 and click the form.

Private 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 one-half width.

HHeight = Printer.TextHeight(Msg) /2	' Get one-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 Example

This 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, and then press F5 and click the form.

Private 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


PopupMenu Method Example

This 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 that includes a Menu control named mnuFile (mnuFile must have at least one submenu).  Copy the code into the Declarations section of the form, and press F5.

Private 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


PrintForm Method Example

This 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 on the printed form, and then press F5 and click the form.

Private Sub Form_Click ()

Dim Msg	' Declare variable.

On Error GoTo ErrorHandler	' Set up error handler.

PrintForm	' Print form.

Exit Sub

ErrorHandler:

Msg = "The form can't be printed."

MsgBox Msg	' Display message.

Resume Next

End Sub


RemoveItem Method Example

This example uses the RemoveItem method to remove entries from a list box.  To try this example, paste the code into the Declarations section of a form with a ListBox control named List1, and then press F5 and click the form.

Private 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


Scale Method Example

This 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, and then press F5 and click the form.

Private 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	' First blue bar.

Line (20, 0)-(30, 55), RGB(255, 0, 0), BF	' First 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


SetText Method Example

This 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, and then press F5 and click the form.

Private 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


Show Method Example

This 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, and then press F5 and click the form.

Private 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


ShowColor, ShowFont, ShowHelp, ShowOpen, ShowPrinter, ShowSave Methods Example

This example uses the CommonDialog control and the ShowColor, ShowFont, ShowHelp, ShowOpen, ShowPrinter, and ShowSave methods to display the common dialog boxes.  To try this example, paste the code into the Declarations section of a form with CommandButton, OptionButton (set the option button's Index property to 0), and CommonDialog controls.  Press F5 and select the option button for the common dialog box you want and choose the command button.

Private Sub Form_Paint ()

Static FlagFormPainted As Integer

' When form is painting for first time,

If FlagFormPainted <> True Then

For i = 1 To 5

Load Option1(i)	' Add five option buttons to array.

Option1(i).Top = Option1(i - 1).Top + 350

Option1(i).Visible = True

Next i

Option1(0).Caption = "Open"	' Put caption on each option button.

Option1(1).Caption = "Save"

Option1(2).Caption = "Color"

Option1(3).Caption = "Font"

 	Option1(4).Caption = "Printer"

Option1(5).Caption = "Help"

Command1.Caption = "Show Dlg"	' Label command button.

FlagFormPainted = True	' Form is done painting.

End If

End Sub

Private Sub Command1_Click ()

If Option1(0).Value Then	' If Open option button selected,

CommonDialog1.ShowOpen	' display Open common dialog box.

ElseIf Option1(1).Value Then	' Or,

CommonDialog1.ShowSave	' display Save common dialog box.

ElseIf Option1(2).Value Then	' Or,

CommonDialog1.ShowColor	' display Color common dialog box.

ElseIf Option1(3).Value Then	' Or,

CommonDialog1.Flags = cdlCFBoth	' Flags property must be set

' to cdlCFBoth, 	' cdlCFPrinterFonts,

' or cdlCFScreenFonts before 	' using ShowFont method.

CommonDialog1.ShowFont	' Display Font common dialog box.

ElseIf Option1(4).Value Then	' Or,

CommonDialog1.ShowPrinter	' display Printer common dialog box.

ElseIf Option1(5).Value Then	' Or,

CommonDialog1.HelpFile = "VB.HLP"

CommonDialog1.HelpCommand = cdlHelpContents

CommonDialog1.ShowHelp	' Display Visual Basic Help contents topic.

End If

End Sub


TextHeight Method Example

The TextHeight method is used to center a line of text vertically on a form.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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 one-half width.

HalfHeight = TextHeight(Msg) / 2	' Calculate one-half height.

CurrentX = ScaleWidth / 2 - HalfWidth	' Set X.

CurrentY = ScaleHeight / 2 - HalfHeight	' Set Y.

Print Msg	' Print message.

End Sub


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, and then press F5 and click the form.

Private 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 one-half width.

HalfHeight = TextHeight(Msg) / 2	' Calculate one-half height.

CurrentX = ScaleWidth / 2 - HalfWidth	' Set X.

CurrentY = ScaleHeight / 2 - HalfHeight	' Set Y.

Print Msg	' Print message.

End Sub


App Object

See Also	Properties

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 file and Help files, and whether or not a previous instance of the application is running.

Note	 For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

App

Remarks

The App object has no events or methods.


See Also

HelpContextID Property

Make OLE DLL File Command


App Object Properties

Comments Property

CompanyName Property

EXEName Property

FileDescription Property

HelpFile Property

hInstance Property

LegalCopyright Property

LegalTrademarks Property

Major Property

Minor Property

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgText Property

OLEServerBusyMsgTitle Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property

Path Property

PrevInstance Property

ProductName Property

Revision Property

StartMode Property

TaskVisible Property

Title Property


CheckBox Control

See Also	Properties	Methods 	Events

A CheckBox control displays an X when selected; the X disappears when the CheckBox is cleared.  Use this control to give the user a True/False or Yes/No option.  You can use CheckBox controls in groups to display multiple choices from which the user can select one or more.

Syntax

CheckBox

Remarks

CheckBox and OptionButton controls function similarly but with an important difference: Any number of CheckBox controls on a form can be selected at the same time.  In contrast, only one OptionButton in a group can be selected at any given time.

To display text next to the CheckBox, set the Caption property.  Use the Value property to determine the state of the control [image] selected, cleared, or unavailable.


See Also

Caption Property

Value Property


CheckBox Control Properties

Alignment Property

Appearance Property

BackColor Property

Caption Property

Container Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

Left Property

MousePointer Property

Name Property

Parent Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Value Property

Visible Property

WhatsThisHelpID Property

Width Property


CheckBox Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


CheckBox Control Events

Click Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


ComboBox Control

See Also	Properties	Methods	Events

A ComboBox control combines the features of a TextBox control and a ListBox control [image] users can enter information in the text box portion or select an item from the list box portion of the control.

Syntax

ComboBox


See Also

ListBox Control

TextBox Control


ComboBox Control Properties

Appearance Property

BackColor Property

Container Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

IntegralHeight Property

ItemData Property

Left Property

ListCount Property

ListIndex Property

List Property

MouseIcon Property

MousePointer Property

Name Property

NewIndex Property

Parent Property

SelLength Property

SelStart Property

SelText Property

Sorted Property

Style Property

TabIndex Property

TabStop Property

Tag Property

Text Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


ComboBox Control Methods

AddItem Method

Clear Method

Drag Method

Move Method

Refresh Method

RemoveItem Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


ComboBox Control Events

Change Event

Click Event

DblClick Event

DragDrop Event

DragOver Event

DropDown Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event


CommandButton Control

See Also	Properties	Methods 	Events

Use a CommandButton control to begin, interrupt, or end a process.  When chosen, a CommandButton appears pushed in and so is sometimes called a push button.

Syntax

CommandButton

Remarks

To display text on a CommandButton control, set its Caption property.  A user can always choose a CommandButton 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 Cancel property of the CommandButton to True.


See Also

Cancel Property

Caption Property

Default Property


CommandButton Control Properties

Appearance Property

BackColor Property

Cancel Property

Caption Property

Container Property

Default Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

Height Property

HelpContextID Property

hWnd Property

Index Property

Left Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Value Property

Visible Property

WhatsThisHelpID Property

Width Property


CommandButton Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


CommandButton Control Events

Click Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


CommonDialog Control

See Also	Properties	Methods

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

Syntax

CommonDialog

Remarks

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

You create dialog boxes for your application by adding the CommonDialog control to a form and setting its properties.  The type of dialog box displayed is determined by the methods of the control.  At run time, a dialog box is displayed when the appropriate method is invoked; at design time, the CommonDialog control is displayed as an icon on a form.  This icon can't be sized.

Under Microsoft Windows 95, the CommonDialog control automatically provides context sensitive help on the interface of the dialog boxes by clicking:

The What's This help button in the title bar then clicking the item for which you want more information.

The right mouse button over the item for which you want more information then selecting the What's This command in the displayed context menu.

The operating system provides the text shown in the Windows 95 Help popup.  However, no topic exists for the Help button displayed with the CommonDialog control by setting the Flags property.

Note   You can't specify where a dialog box is displayed.

Distribution Note   The CommonDialog control is a custom control, which is a separate file with an .OCX extension.  To use the CommonDialog control in your application, you must add the COMDLG16.OCX or COMDLG32.OCX file to the project.  To automatically include this custom control in new projects, add the file you need to AUTOLOAD.VBP.  When distributing your application, install the .OCX file in the user's Microsoft Windows SYSTEM directory.  For more information on how to add a custom control to a project, see the Programmer's Guide.


See Also

Call Statement

Declare Statement

Setup Toolkit Overview


CommonDialog Control Properties

Color Dialog Properties

File Dialog Properties

Font Dialog Properties

Print Dialog Properties


Color Dialog Box Properties (CommonDialog)

Action Property

CancelError Property

Color Property

Flags Property

HelpCommand Property

HelpContext Property

HelpFile Property

HelpKey Property

Object Property


File Dialog Box Properties (CommonDialog)

Action Property

CancelError Property

DefaultExt Property

DialogTitle Property

FileName Property

FileTitle Property

Filter Property

FilterIndex Property

Flags Property

HelpCommand Property

HelpContext Property

HelpFile Property

HelpKey Property

InitDir Property

MaxFileSize Property

Object Property


Font Dialog Box Properties (CommonDialog)

Action Property

CancelError Property

Flags Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

HelpCommand Property

HelpContext Property

HelpFile Property

HelpKey Property

Max Property

Min Property

Object Property


Print Dialog Box Properties (CommonDialog)

Action Property

CancelError Property

Copies Property

Flags Property

FromPage Property

hDC Property

HelpCommand Property

HelpContext Property

HelpFile Property

HelpKey Property

Max Property

MaxFileSize Property

Min Property

Object Property

PrinterDefault Property

ToPage Property


CommonDialog Control Methods

ShowColor Method

ShowFont Method

ShowHelp Method

ShowOpen Method

ShowPrinter Method

ShowSave Method


Controls Collection

See Also	Properties

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.

Syntax

object.Controls(index)

The Controls collection syntax has these parts:

Part	Description

object	An object expression that evaluates to a Form object.

index	An integer with a range from 0 to Forms.Count - 1.

Remarks

The Controls collection enumerates loaded controls on a form and is useful for iterating through them.  The Controls collection  identifies an intrinsic form-level variable named Controls.  If you omit the optional object placeholder, you must include the Controls keyword.  If you include object, you can omit the Controls keyword.  For example, the following two lines of code have the same effect:

MyForm.Controls(6).Top = MyForm.Controls(5).Top + increment

MyForm(6).Top = MyForm(5).Top + increment

You can pass Controls(index) to a function whose argument is specified as a Controls class.


See Also

Forms Object, Forms Collection


Controls Collection Properties

Count Property


DirListBox Control

See Also	Properties	Methods 	Events

A DirListBox control displays directories and paths at run time.  Use this control to display a hierarchical list of directories.  You can create dialog boxes that, for example, enable a user to open a file from a list of files in all available directories.

Syntax

DirListBox

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in a list.  If you also display the DriveListBox and FileListBox controls, you can write code to synchronize them with the DirListBox control and with each other.


See Also

DriveListBox Control

FileListBox Control

List Property

ListCount Property

ListIndex Property


DirListBox Control Properties

Appearance Property

BackColor Property

Container Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

Left Property

List Property

ListCount Property

ListIndex Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

Path Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


DirListBox Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


DirListBox Control Events

Change Event

Click Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


DriveListBox Control

See Also	Properties	Methods 	Events

A DriveListBox control enables a user to select a valid disk drive at run time.  Use this control to display a list of all the valid drives in a user's system.  You can create dialog boxes that enable the user to open a file from a list of files on a disk in any available drive.

Syntax

DriveListBox

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.  If you also display the DirListBox and FileListBox controls, you can write code to synchronize them with the DriveListBox control and with each other.


See Also

DirListBox Control

FileListBox Control

List Property

ListCount Property

ListIndex Property


DriveListBox Control Properties

Appearance Property

BackColor Property

Container Property

DragIcon Property

DragMode Property

Drive Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

Left Property

List Property

ListCount Property

ListIndex Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


DriveListBox Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


DriveListBox Control Events

Change Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event


FileListBox Control

See Also	Properties	Methods 	Events

A FileListBox control locates and lists files in the directory specified by the Path property at run time.  Use this control to display a list of files selected by file type.  You can create dialog boxes in your application that, for example, enable the user to select a file or group of files.

Syntax

FileListBox

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.  If you also display the DirListBox and DriveListBox controls, you can write code to synchronize them with the FileListBox control and with each other.


See Also

DirListBox Control

DriveListBox Control

List Property

ListCount Property

ListIndex Property

Path Property


FileListBox Control Properties

Appearance Property

Archive Property

BackColor Property

Container Property

DragIcon Property

DragMode Property

Enabled Property

FileName Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

Hidden Property

hWnd Property

Index Property

Left Property

List Property

ListCount Property

ListIndex Property

MouseIcon Property

MousePointer Property

MultiSelect Property

Name Property

Normal Property

Parent Property

Path Property

Pattern Property

ReadOnly Property

Selected Property

System Property

TabIndex Property

TabStop Property

Tag Property

Top Property

TopIndex Property

Visible Property

WhatsThisHelpID Property

Width Property


FileListBox Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


FileListBox Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event

PathChange Event

PatternChange Event


Form Object, Forms Collection

See Also	Example	Properties	Methods 	Events

A Form object is a window or dialog box that makes up part of an application's user interface.

A Forms collection is 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.

Note	 For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

Form

Forms(index)

The placeholder index represents an integer with a range from 0 to Forms.Count - 1.

Remarks

You can use the Forms collection to iterate through all loaded forms in an application.  It identifies an intrinsic global variable named Forms.  You can pass Forms(index) to a function. whose argument is specified as a Forms class.

Forms have properties that determine aspects of their appearance, such as position, size, and color; and aspects of their behavior, such as whether or not they are resizable.

Forms can also respond to events initiated by a user or triggered by the system.  For example, you could write code in a form's Click event procedure that would enable 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 using 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 MDI Form command on the Insert 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 keyword in Dim, 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   Setting BorderStyle to 0 removes the border.  If you want your form to have a border without the title bar, Control-menu box, Maximize button, and Minimize button, delete any text from the form's Caption property, and set the form's ControlBox, MaxButton, and MinButton properties to False.

Form is an object data 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 pass an argument to a procedure as type Form.

Forms also can act as sources in a DDE conversation, with a Label, PictureBox, or TextBox control furnishing the data.

You can access the collection of controls on a Form using the Controls collection.  For example, to hide all the controls on an Form you can use code similar to the following:

For Each Control in Form1.Controls

Control.Visible = False

Next Control


See Also

Controls Collection

Count Property

Dim Statement

Hide Method

Label Control

Make OLE DLL File Command

MDIChild Property

MDIForm Object

Move Method

PictureBox Control

Set Statement

Static Statement

TextBox Control


Form Object, Forms Collection Properties

Legend

ActiveControl Property

ActiveForm Property

AutoRedraw Property

Appearance Property

BackColor Property

BorderStyle Property

Caption Property

ClipControls Property

ControlBox Property

Count Property

CurrentX Property

CurrentY Property

DrawMode Property

DrawStyle Property

DrawWidth Property

Enabled Property

FillColor Property

FillStyle Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontTransparent Property

FontUnderline Property

ForeColor Property

hDC Property

Height Property

HelpContextID Property

hWnd Property

Icon Property

Image Property

KeyPreview Property

Left Property

LinkMode Property

LinkTopic Property

MaxButton Property

MDIChild Property

MinButton Property

MouseIcon Property

MousePointer Property

Name Property

NegotiateMenus Property

NewEnum Property

Picture Property

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleTop Property

ScaleWidth Property

ShowInTaskbar Property

Tag Property

Top Property

Visible Property

WhatsThisButton Property

WhatsThisHelp Property

Width Property

WindowState Property


Form Object, Forms Collection Methods

Legend

Circle Method

Cls Method

Hide Method

Item Method

Line Method

Move Method

PaintPicture Method

Point Method

PopupMenu Method

Print Method

PrintForm Method

PSet Method

Refresh Method

Scale Method

ScaleX Method

ScaleY Method

SetFocus Method

Show Method

TextHeight Method

TextWidth Method

WhatsThisMode Method

ZOrder Method


Form Object, Forms Collection Events

Activate Event

Click Event

DblClick Event

Deactivate Event

DragDrop Event

DragOver Event

GotFocus Event

Initialize Event

KeyDown Event

KeyPress Event

KeyUp Event

LinkClose Event

LinkError Event

LinkExecute Event

LinkOpen Event

Load Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event

Paint Event

QueryUnload Event

Resize Event

Terminate Event

Unload Event


Frame Control

See Also	Properties	Methods 	Events

A Frame control provides an identifiable grouping for controls.  You can also use a Frame to subdivide a form functionally [image] for example, to separate groups of OptionButton controls.

Syntax

Frame

Remarks

To group controls, first draw the Frame control, and then draw the controls inside the Frame.  This enables you to move the Frame and the controls it contains 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.


See Also

OptionButton Control


Frame Control Properties

Appearance Property

BackColor Property

Caption Property

ClipControls Property

Container Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

Left Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

TabIndex Property

Tag Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


Frame Control Methods

Drag Method

Move Method

Refresh Method

ShowWhatsThis Method

ZOrder Method


Frame Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

MouseDown Event

MouseMove Event

MouseUp Event


Grid Control

See Also	Properties	Methods 	Events

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 in code.

Syntax

Grid

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 a 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 the text in a cell 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.  This control can't have more than 16352 rows and 5450 columns.

When a new element of a control array is loaded at run time, the new element doesn't inherit the original control's run-time properties.

Distribution Note   The Grid control is a custom control, which is a separate file with an .OCX extension.  To use the Grid control in your application, you must add the GRID16.OCX or GRID32.OCX file to the project.  To automatically include this custom control in new projects, add the file you need to AUTOLOAD.VBP.  When distributing your application, install the custom control file in the user's Microsoft Windows SYSTEM directory.  For more information on how to add a custom control to a project, see the Programmer's Guide.


See Also

Col Property

ColWidth Property

Row Property

RowHeight Property

Text Property


Grid Control Properties

BackColor Property

BorderStyle Property

CellSelected Property

Clip Property

Col Property

ColAlignment Property

ColIsVisible Property

ColPos Property

Cols Property

ColWidth Property

Container Property

DragIcon Property

DragMode Property

Enabled Property

FillStyle Property

FixedAlignment Property

FixedCols Property

FixedRowsProperty

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

GridLines Property

GridLineWidth Property

Height Property

HelpContextID Property

HighLight Property

hWnd Property

Index Property

Left Property

LeftCol Property

MouseIcon Property

MousePointer Property

Name Property

Object Property

Parent Property

Picture Property

Row Property

RowHeight Property

RowIsVisible Property

RowPos Property

Rows Property

ScrollBars Property

SelEndCol Property

SelEndRow Property

SelStartCol Property

SelStartRow Property

TabIndex Property

TabStop Property

Tag Property

Text Property

Top Property

TopRow Property

Visible Property

WhatsThisHelpID Property

Width Property


Grid Control Methods

AddItem Method

Drag Method

Move Method

Refresh Method

RemoveItem Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


Grid Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event

RowColChange Event

SelChange Event


HScrollBar, VScrollBar Controls

See Also	Properties	Methods 	Events

Scroll bars provide easy navigation through a long list of items or a large amount of information.  They can also 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 volume of a computer game or to view the time elapsed in a timed process.

Syntax

HScrollBar

VScrollBar

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 for the control.

To specify the amount of change to report in a scroll bar, use the LargeChange property for clicking in the scroll bar, and the SmallChange property for clicking the arrows at the ends of the scroll bar.  The scroll bar's Value property increases or decreases by the values 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.


See Also

LargeChange Property

Max Property

Min Property

SmallChange Property

Value Property


HScrollBar Control, VScrollBar Control Properties

Appearance Property

Container Property

DragIcon Property

DragMode Property

Enabled Property

Height Property

HelpContextID Property

hWnd Property

Index Property

LargeChange Property

Left Property

Max Property

Min Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

SmallChange Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Value Property

Visible Property

WhatsThisHelpID Property

Width Property


HScrollBar Control, VScrollBar Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


HScrollBar Control, VScrollBar Control Events

Change Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

Scroll Event


Image Control

See Also	Properties	Methods 	Events

Use the Image control to display a graphic.

Syntax

Image

Remarks

The Image control uses fewer system resources and repaints faster than a PictureBox control, but it supports only a subset of the PictureBox properties, events, and methods.  Use the Stretch property to determine whether the graphic is scaled to fit the control or vice versa.  Although you can place an Image control within a container, an Image control can't act as a container.


See Also

Graphical Objects

PictureBox Control

Stretch Property


Image Control Properties

Appearance Property

BorderStyle Property

Container Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Height Property

Index Property

Left Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

Picture Property

Stretch Property

Tag Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


Image Control Methods

Drag Method

Move Method

Refresh Method

ShowWhatsThis Method

ZOrder Method


Image Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

MouseDown Event

MouseMove Event

MouseUp Event


Label Control

See Also	Properties	Methods 	Events

A Label control is a graphical control you can use to display text that a user can't change directly.

Syntax

Label

Remarks

You can write code that changes the text displayed by a Label control in response to events at run time.  For example, if your application takes a few minutes to commit a change, you can display a processing-status message in a Label.  You can also use a Label to identify a control, such as a TextBox control, that doesn't 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 control can also act as a destination in a DDE conversation.  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 properties have been set, Visual Basic attempts to initiate the conversation and displays a message if it's unable to do so.

Set the UseMnemonic property to True if you want to define a character in the Caption property of the Label as an access key.  When you define an access key in a Label control, the user can press and hold down ALT+ the character you designate to move the focus to the next control in the tab order.


See Also

AutoSize Property

Caption Property

DataField Property

DataSource Property

Graphical Objects

LinkItem Property

LinkMode Property

LinkTopic Property

TabIndex Property

TextBox Control

WordWrap Property


Label Control Properties

Alignment Property

Appearance Property

AutoSize Property

BackColor Property

BackStyle Property

BorderStyle Property

Caption Property

Container Property

DataChanged Property

DataSource Property

DataField Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

Index Property

Left Property

LinkItem Property

LinkMode Property

LinkTimeout Property

LinkTopic Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

TabIndex Property

Tag Property

Top Property

UseMnemonic Property

Visible Property

WhatsThisHelpID Property

Width Property

WordWrap Property


Label Control Methods

Drag Method

LinkExecute Method

LinkPoke Method

LinkRequest Method

Move Method

Refresh Method

ShowWhatsThis Method

ZOrder Method


Label Control Events

Change Event

Click Event

DblClick Event

DragDrop Event

DragOver Event

LinkClose Event

LinkError Event

LinkNotify Event

LinkOpen Event

MouseDown Event

MouseMove Event

MouseUp Event


Line Control

See Also	Properties	Methods

A Line control is a graphical control displayed as a horizontal, vertical, or diagonal line.

Syntax

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 remain on the form even if the AutoRedraw property setting is False.  Line controls can be displayed on forms, in picture boxes, and in frames.  You can't 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, and Y2 properties.  The effect of setting the BorderStyle property depends on the setting of the BorderWidth property.  If BorderWidth isn't 1 and BorderStyle isn't 0 or 6, BorderStyle is set to 1.


See Also

BorderStyle Property

BorderWidth Property

Frame Control

Graphical Objects

Line Method

Move Method

PictureBox Control


Line Control Properties

Appearance Property

BorderColor Property

BorderStyle Property

BorderWidth Property

Container Property

DrawMode Property

Index Property

Name Property

Parent Property

Tag Property

Visible Property

X1 Property

X2 Property

Y1 Property

Y2 Property


Line Control Methods

Refresh Method

ZOrder Method


ListBox Control

See Also	Properties	Methods 	Events

A ListBox control displays a list of items from which the user can select one or more.  If the number of items exceeds the number that can be displayed, a scroll bar is automatically added to the ListBox control.

If no item is selected, the ListIndex property value is -1.  The first item in the list is ListIndex 0, and the value of the ListCount property is always one more than the largest ListIndex value.

Syntax

ListBox

Remarks

To add or delete items in a ListBox control, use the AddItem or RemoveItem method.  Set the List, ListCount, and ListIndex properties to enable a user to access items in the ListBox.


See Also

AddItem Method

List Property

ListCount Property

ListIndex Property

RemoveItem Method


ListBox Control Properties

Appearance Property

BackColor Property

Columns Property

Container Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

IntegralHeight Property

ItemData Property

Left Property

List Property

ListCount Property

ListIndex Property

MouseIcon Property

MousePointer Property

MultiSelect Property

Name Property

NewIndex Property

Parent Property

SelCount Property

Selected Property

Sorted Property

TabIndex Property

TabStop Property

Tag Property

Text Property

Top Property

TopIndex Property

VisibleProperty

WhatsThisHelpID Property

Width Property


ListBox Control Methods

AddItem Method

Clear Method

Drag Method

Move Method

Refresh Method

RemoveItem Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


ListBox Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


MDIForm Object

See Also	Properties	Methods 	Events

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.

Note	 For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

MDIForm

Remarks

You create an MDIForm object by choosing MDI Form from the Insert menu.

An application can have only one MDIForm object but many MDI child forms.  If an MDI child form has menus, the child form's menu bar automatically replaces the MDIForm object's menu bar when the MDI child form is active.  A minimized MDI child form is displayed as an icon within the MDIForm.

An MDIForm object can contain only Menu and PictureBox controls and custom controls that have an Align property.  To place other controls on an MDIForm, 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 MDIForm, but you can't use this method to display text on the MDIForm itself.

An MDIForm object can't be modal.

MDI child forms are designed independently of the MDIForm, but are always contained within the MDIForm at run time.

You can access the collection of controls on an MDIForm using the Controls collection.  For example, to hide all the controls on an MDIForm you can use code similar to the following:

For Each Control in MDIForm1.Controls

Control.Visible = False

Next Control

The Count property of the MDIForm tells you the number of controls in the Controls collection.


See Also

Make OLE DLL File Command

MDIChild Property

Print Method


MDIForm Object Properties

ActiveControl Property

ActiveForm Property

Appearance Property

AutoShowChildren

BackColor Property

Caption Property

Enabled Property

Height Property

HelpContextID Property

hWnd Property

Icon Property

Left Property

LinkMode Property

LinkTopic Property

MouseIcon Property

MousePointer Property

Name Property

Picture Property

ScaleHeight Property

ScaleWidth Property

ScrollBars Property

Tag Property

Top Property

Visible Property

WhatsThisHelp Property

Width Property

WindowState Property


MDIForm Object Methods

Arrange Method

Hide Method

Move Method

PopupMenu Method

SetFocus Method

Show Method

WhatsThisMode Method

ZOrder Method


MDIForm Object Events

Activate Event

Click Event

DblClick Event

Deactivate Event

DragDrop Event

DragOver Event

Initialize Event

LinkClose Event

LinkError Event

LinkExecute Event

LinkOpen Event

Load Event

MouseDown Event

MouseMove Event

MouseUp Event

QueryUnload Event

Resize Event

Terminate Event

Unload Event


Menu Control

See Also	Properties	Events

A Menu control displays a custom menu for your application.  A menu can include commands, submenus, and separator bars.  Each menu you create can have up to four levels of submenus.

Syntax

Menu

Remarks

To create a Menu control, use the Menu Editor.  Enter the name of the Menu control 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, select the Checked box.

While you can set some Menu control properties using the Menu Editor, all Menu control properties are displayed in the Properties window.  To display the properties of a Menu control, select the menu name in the Objects list at the top of the Properties window.

When you create an MDI application, the menu bar on the MDI child form replaces the menu bar on the MDIForm object when the child form is active.


See Also

MDIForm Object

Menu Editor


Menu Control Properties

Appearance Property

Caption Property

Checked Property

Enabled Property

HelpContextID Property

Index Property

Name Property

NegotiatePosition Property

Parent Property

ShortCut Property

Tag Property

Visible Property

WindowList Property


Menu Control Events

Click Event


OptionButton Control

See Also	Properties	Methods 	Events

An OptionButton control displays an option that can be turned on or off.

Syntax

OptionButton

Remarks

Usually, OptionButton controls are used in an option group to display options from which the user selects only one.  You group OptionButton controls by drawing them inside a container such as a Frame control, a PictureBox control, or a form.  To group OptionButton controls in a Frame or PictureBox, draw the Frame or PictureBox first, and then draw the OptionButton controls inside.  All OptionButton controls within the same container act as a single group.

While OptionButton controls and CheckBox controls may appear to function similarly, there is an important difference:  When a user selects an OptionButton, the other OptionButton controls in the same group are automatically unavailable.  In contrast, any number of CheckBox controls can be selected.


See Also

CheckBox Control

Form Object

Frame Object

PictureBox Control


OptionButton Control Properties

Alignment Property

Appearance Property

BackColor Property

Caption Property

Container Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

hWnd Property

Index Property

Left Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Value Property

Visible Property

WhatsThisHelpID Property

Width Property


OptionButton Control Methods

Drag Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


OptionButton Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


PictureBox Control

See Also	Properties	Methods 	Events

A PictureBox control can display a graphic from a bitmap, icon, or metafile.  It clips the graphic if the control isn't large enough to display the entire image.

Syntax

PictureBox

Remarks

You can also use a PictureBox control to group OptionButton controls and to display output from graphics methods and text written with the Print method.

To make a PictureBox control automatically resize to display an entire graphic, set its AutoSize property to True.

To create animation or simulation, you can manipulate graphics properties and methods in code.  Graphics properties and events are useful for run-time print operations, such as modifying the format of a screen form for printing.

A PictureBox control can also act as a destination link in a DDE conversation.

PictureBox is the only standard Visual Basic control that you can place in the internal area of an MDI form.  You can use it to group controls at the top or bottom of the internal area to create a toolbar or status bar.


See Also

AutoSize Property

MDIForm Object

Print Method


PictureBox Control Properties

Align Property

Appearance Property

AutoRedraw Property

AutoSize Property

BackColor Property

BorderStyle Property

ClipControls Property

Container Property

CurrentX Property

CurrentY Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

DrawMode Property

DrawStyle Property

DrawWidth Property

Enabled Property

FillColor Property

FillStyle Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontTransparent Property

FontUnderline Property

ForeColor Property

hDC Property

Height Property

HelpContextID Property

hWnd Property

Image Property

Index Property

Left Property

LinkItem Property

LinkMode Property

LinkTimeout Property

LinkTopic Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

Picture Property

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleTop Property

ScaleWidth Property

TabIndex Property

TabStop Property

Tag Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


PictureBox Control Methods

Circle Method

Cls Method

Drag Method

Line Method

LinkExecute Method

LinkPoke Method

LinkRequest Method

LinkSend Method

Move Method

PaintPicture Method

Point Method

Print Method

PSet Method

Refresh Method

Scale Method

ScaleX Method

ScaleY Method

SetFocus Method

ShowWhatsThis Method

TextHeight Method

TextWidth Method

ZOrder Method


PictureBox Control Events

Change Event

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LinkClose Event

LinkError Event

LinkNotify Event

LinkOpen Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event

Paint Event

Resize Event


Shape Control

See Also	Properties	Methods

The Shape control is a graphical control displayed as a rectangle, square, oval, circle, rounded rectangle, or rounded square.

Syntax

Shape

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 can't act as a container.  The effect of setting the BorderStyle property depends on the setting of the BorderWidth property.  If BorderWidth isn't 1 and BorderStyle isn't 0 or 6, BorderStyle is set to 1.


See Also

Circle Method

Frame Control

Graphical Objects

Line Method

PictureBox Control


Shape Control Properties

Appearance Property

BackColor Property

BackStyle Property

BorderColor Property

BorderStyle Property

BorderWidth Property

Container Property

DrawMode Property

FillColor Property

FillStyle Property

Height Property

Index Property

Left Property

Name Property

Parent Property

Shape Property

Tag Property

Top Property

Visible Property

Width Property


Shape Control Methods

Move Method

Refresh Method

ZOrder Method


TextBox Control

See Also	Properties	Methods 	Events

A TextBox control, sometimes called an edit field or edit control, displays information entered at design time, entered by the user, or assigned to the control in code at run time.

Syntax

TextBox

Remarks

To display multiple lines of text in a TextBox control, set the MultiLine property to True.  If a multiple-line TextBox doesn't have a horizontal scroll bar, text wraps automatically even when the TextBox is resized.  To customize the scroll bar combination on a TextBox, set the ScrollBars property.

If you set the MultiLine property to True, you can use the Alignment property to set the alignment of text within the TextBox.  The text is left-justified by default.  If the MultiLine property is False, setting the Alignment property has no effect.

A TextBox control can also act as a destination link in a DDE conversation.


See Also

Alignment Property

MultiLine Property

ScrollBars Property


TextBox Control Properties

Alignment Property

Appearance Property

BackColor Property

BorderStyle Property

Container Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

FontBold Property

FontItalic Property

FontName Property

FontSize Property

FontStrikethru Property

FontUnderline Property

ForeColor Property

Height Property

HelpContextID Property

HideSelection Property

hWnd Property

Index Property

Left Property

LinkItem Property

LinkMode Property

LinkTimeout Property

LinkTopic Property

Locked Property

MaxLength Property

MouseIcon Property

MousePointer Property

MultiLine Property

Name Property

Parent Property

PasswordChar Property

ScrollBars Property

SelLength Property

SelStart Property

SelText Property

TabIndex Property

TabStop Property

Tag Property

Text Property

Top Property

Visible Property

WhatsThisHelpID Property

Width Property


TextBox Control Methods

Drag Method

LinkExecute Method

LinkPoke Method

LinkRequest Method

Move Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


TextBox Control Events

Change Event

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LinkClose Event

LinkError Event

LinkNotify Event

LinkOpen Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


Timer Control

See Also	Properties	Events

A Timer control can execute code at regular intervals by causing a Timer event.

Syntax

Timer

Remarks

The Timer control, invisible to the user, is useful for background processing.

You can't set the Enabled property of a Timer for a multiple selection of controls other than Timer controls.


See Also

Enabled Property

Timer Event


Timer Control Properties

Enabled Property

Index Property

Interval Property

Left Property

Name Property

Parent Property

Tag Property

Top Property


Timer Control Events

Timer Event


Forms Collection Example

This example fills a list box with the captions of all the currently loaded forms.

Private 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 Example

This example enables 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 Not TypeOf Frm.Controls(I) Is Menu Then

Frm.Controls(I).Enabled = State

End If

Next I

End Sub


OLE Container Control

See Also	Properties	Methods 	Events

The OLE container control enables you to add insertable objects to the forms in your Visual Basic applications.  With the OLE container control, you can:

Create a placeholder in your application for an insertable object.  At run time you can create the object that is displayed within the OLE container control or change an object you placed within the OLE container control at design time.

Create a linked object in your application.

Bind the OLE container control to a database using the Data control.

You either create the object at design time using standard OLE dialog boxes (Insert Object, Paste Special, and so on) or at run time by setting the appropriate properties.

Using the OLE Container Control's Pop-up Menus

Each time you draw an OLE container control on a form, the Insert Object dialog box is displayed.  Use this dialog box to create a linked or embedded object.  If you choose Cancel, no object is created.

At design time, click the OLE container 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 container control as shown in the following table:

Command	Enabled in pop-up menu when

Insert Object	Always enabled.

Paste Special	Clipboard object contains a valid object.

Delete Embedded Object	OLE container control contains an embedded object.

Delete Linked Object	OLE container control contains a linked object.

Create Link	SourceDoc property is set.

Create Embedded Object	Class or SourceDoc property is set.

An OLE container control can contain only one object at a time.  You can create a linked or embedded object in several ways:

Use the Insert Object or Paste Special dialog boxes (run time or design time).

Set the Class property in the Properties window, click the OLE container control with the right mouse button, and then select the appropriate command (design time only).

Use the appropriate method of the OLE container control.

Finding Class Names

You can get a list of the class names available to your application by selecting the Class property in the Properties window and clicking the Properties button.

Note   The Insert Object dialog box doesn't display a list of class names.  This dialog box displays user-friendly names for each class of object, which are generally longer and more easily understood.


OLE Container Control See Also
See Also

CreateObject Function

GetObject Function

Object Property

OLE Fundamentals

Open Statement


OLE Container Control Properties

Action Property (OLE Container)

Appearance Property

AppIsRunning Property

AutoActivate Property

AutoVerbMenu Property

BackColor Property

BackStyle Property

BorderStyle Property

Class Property

Container Property

Data Property

DataChanged Property

DataField Property

DataSource Property

DataText Property

DisplayType Property

DragIcon Property

DragMode Property

Enabled Property

FileNumber Property

Format Property

Height Property

HelpContextID Property

HostName Property

hWnd Property

Index Property

Left Property

lpOleObject Property

MiscFlags Property

MouseIcon Property

MousePointer Property

Name Property

Object Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property

ObjectVerbFlags Property

ObjectVerbs Property

ObjectVerbsCount Property

OLEDropAllowed Property

OLEType Property

OLETypeAllowed Property

Parent Property

PasteOK Property

Picture Property

SizeMode Property

SourceDoc Property

SourceItem Property

TabIndex Property

TabStop Property

Tag Property

Top Property

UpdateOptions Property

Verb Property

Visible Property

WhatsThisHelpID Property

Width Property


OLE Container Control Methods

Close Method (OLE Container)

Copy Method

CreateEmbed Method

CreateLink Method

Delete Method (OLE Container)

DoVerb Method

Drag Method

FetchVerbs Method

InsertObjDlg Method

Move Method

Paste Method

PasteSpecialDlg Method

ReadFromFile Method

Refresh Method

SaveToFile Method

SaveToOle1File Method

SetFocus Method

ShowWhatsThis Method

Update Method (OLE Container)

ZOrder Method


OLE Container Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event

ObjectMove Event

Resize Event

Updated Event


OLE Fundamentals

Object linking and embedding (OLE) is a technology that enables a programmer of Windows-based applications to create an application that can display data from many different applications and enables 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 following terms and concepts are fundamental to understanding how to use OLE in Visual Basic.

Objects

An object refers to a discrete unit of data supplied by an 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.

There are three ways to create an object in Visual Basic:

Add the object to the Toolbox using the Custom Controls command on the Tools menu, and then draw the object directly on a form.  This technique embeds the object within the interface of a form in your application.

Use the CreateObject or GetObject functions to create the object in code.  This technique creates the object in a running instance of the application that provides the object.

Embed or link the object within an OLE container control.  This technique enables you to change objects on the form at run time, create linked objects, and bind the OLE container control to a Data control.

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 an OLE container control supports OLE Automation, you can access its properties and methods using the Object property.  If you draw the object directly on a form or create it in code, you can directly access the properties and methods of the object.

Class

The application that provides the object's data and the type of data the object contains determines the object's class.  You can get a list of the class names available to your application by selecting the Class property in the Properties window and clicking the Properties button.

Container Application

An application that receives and displays an object's data is a container application.  For example, a Visual Basic application that uses an OLE container control to embed or link data from another application is a container application.

Note   In Visual Basic version 3.0, applications that provide access to objects were called source applications.  Applications used to contain objects were referred to as destination applications.

Linked Objects

Data associated with a linked object is stored by the application that supplied the object.  The application only stores link references that display a snapshot of the source data.

When you link an object, any application containing a link to that object can access the object's data and change it.  For example, if you link a text file to a Visual Basic application, the text file can be modified by any application linked to it.  The modified version appears in all documents linked to this text file.  You use the OLE container control to create a linked object in your Visual Basic application.

Embedded Objects

When you create an embedded object, all the data associated with the object is contained in the object.  For example, if a spreadsheet were an embedded object, all the data associated with the cells would be contained in the OLE container control or insertable object, 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 so the user can edit those cells.  When an object is embedded in an application, no other application has access to the data in the embedded object.  You can use embedded objects when you want only your application to maintain data that is produced and edited in another application.


Class Property

See Also	Applies To

Returns or sets the class name of an embedded object.

Syntax

object.Class [ = string]

The Class property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying the class name.

Remarks

A class name defines the type of an object.  Applications that support OLE or OLE Automation fully qualify the class names of their objects using either of the following syntaxes:

application.objecttype.version

objecttype.version

The syntax for OLE class names has the following parts:

Part	Description

application	The name of the application that supplies the object.

objecttype	The object's name as defined in the object library.

version	The version number of the object or application that supplies the object.

For example, Microsoft Excel version 5.0 supports a number of objects, including worksheets and charts.  Their class names are Excel.Sheet.5 and Excel.Chart.5.  Microsoft WordArt version 2.0 supports a single object with the class name MSWordArt.2.

Note   Some OLE programming documentation refers to the class name syntax as a programmatic ID.

Creating an object at design time using the Insert Object or Paste Special dialog boxes, automatically sets the Class property of the OLE container control 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 Properties button.

Copying an object from the system Clipboard updates the Class property.  For example, if you paste a Microsoft Excel chart from the system Clipboard into an OLE container control that previously contained a Microsoft Excel worksheet, the Class property setting changes from Excel.Sheet.5 to Excel.Chart.5.  You can paste an object from the system Clipboard at run time with the Paste method or the PasteSpecialDlg method.


Class Property Applies To

OLE Container Control


Class Property See Also
See Also

OLE Fundamentals

Paste Method

PasteOK Property

PasteSpecialDlg Method


ObjectVerbFlags Property

See Also	Applies To

Returns the menu state for each verb in the ObjectVerbs array.

Syntax

object.ObjectVerbFlags(number)

The ObjectVerbFlags property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression indicating the element in the array.

Return Values

The ObjectVerbFlags property returns the following values:

Constant	Value	Description

vbOLEFlagChecked	&H0008	The menu item is checked.

vbOLEFlagDisabled	&H0002	The menu item is disabled (but not dimmed).

vbOLEFlagEnabled	&H0000	The menu item is enabled.

vbOLEFlagGrayed	&H0001	The menu item is dimmed.

vbOLEFlagSeparator	&H0800	The menu item is a separator bar.

Note   These constants are listed in the Visual Basic (VB) object library in the Object Browser.

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 dimmed, 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 is displayed.


ObjectVerbFlags Property Applies To

OLE Container Control


ObjectVerbFlags Property See Also
See Also

AutoVerbMenu Property

ObjectVerbs Property

ObjectVerbsCount Property

Verb Property


SizeMode Property

See Also	Applies To

Returns or sets a value specifying how the OLE container control is sized or how its image is displayed when it contains an object.

Syntax

object.SizeMode [ = value]

The SizeMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer or constant specifying how the control is sized or how its image is displayed, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbOLESizeClip	0 	(Default) Clip.  The object is displayed in actual size.  If the object is larger than the OLE container control, its image is clipped by the control's borders.

vbOLESizeStretch	1	Stretch.  The object's image is sized to fill the OLE container control.  The image may not maintain the original proportions of the object.

vbOLESizeAutoSize	2	Autosize.  The OLE container control is resized to display the entire object.

vbOLESizeZoom	3	Zoom.  The object is resized to fill the OLE container control as much as possible while still maintaining the original proportions of the object.

Remarks

When SizeMode is set to 2 (Autosize), the OLE container control is automatically resized when the display size of an object changes.  When this occurs, the Resize event is invoked before the OLE container control is automatically resized.  The heightnew and widthnew arguments in the Resize event procedure indicate the optimal size for displaying the object (this size is determined by the application that created the object).  You can size the control by changing the values of the heightnew and widthnew arguments in the Resize event procedure.


SizeMode Property Applies To

OLE Container Control


SizeMode Property See Also
See Also

Resize Event

Updated Event


Data Property

See Also	Applies To

Returns or sets a handle to a memory object or graphical device interface (GDI) object containing data in a specified format.  Not available at design time.

Syntax

object.Data [ = number]

The Data property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying the handle.

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 object or GDI object.

You can get a list of acceptable formats for an object using the ObjectAcceptFormats and ObjectGetFormats properties.

Setting this property to 0 frees the memory associated with the handle.

Tip   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 Property Applies To

OLE Container Control


Data Property See Also
See Also

CreateObject Function

DataText Property

Format Property

GetObject Function

Object Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property

OLE Automation


DataText Property

See Also	Example 	Applies To

Returns a string from or sets a string for the specified object.

Syntax

object.DataText [ = string]

The DataText property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying the string.

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.

If you're using the 16-bit version of Visual Basic, the DataText string must be less than 64K.  If you're using the 32-bit version of Visual Basic, the DataText string can be as large as available memory permits.

Tip   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.


DataText Property Applies To

OLE Container Control


DataText Property See Also
See Also

CreateObject Function

Data Property

Format Property

GetObject Function

Object Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property

OLE Automation


FileNumber Property

See Also	Applies To

Returns or sets the file number to be used when saving or loading an object, or returns the last file number used.  Not available at design time.

Note   The FileNumber property is included for compatibility with the Action property in earlier versions.  For current functionality, use the SaveToFile and ReadFromFile methods.

Syntax

object.FileNumber [ = number]

The FileNumber property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying the file number.

Remarks

The file number must correspond to an open, binary file.

You can use this property to specify the number of the file to be opened with the ReadFromFile method or saved with the SaveToFile or SaveToOle1File methods.


FileNumber Property See Also
See Also

ReadFromFile Method

SaveToFile Method

SaveToOle1File Method


FileNumber Property Applies To

OLE Container Control


HostName Property

See Also 	Applies To

Returns or sets the user-readable host name of your Visual Basic application.

Syntax

object.HostName [ = name]

The HostName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

name	A string expression specifying the host name.

Remarks

When editing an object, the HostName property setting may be displayed in the object's window title.  However, some applications that provide objects don't display HostName.


HostName Property Applies To

OLE Container Control


HostName Property See Also
See Also

OLE Fundamentals


lpOleObject Property

Applies To

Returns the address of the object.

Syntax

object.lpOleObject

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Many function calls in the OLE DLLs require the address of an object as an argument.  Pass the value specified in the lpOleObject property when making API calls to the OLE 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 container control, the result is unpredictable.

The address returned by this property is a far pointer to the lpOleObject interface for the active object.


lpOleObject Property Applies To

OLE Container Control


ObjectAcceptFormats Property

See Also	Example 	Applies To

Returns the list of formats an object can accept.

Syntax

object.ObjectAcceptFormats(number)

The ObjectAcceptFormats property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression indicating the element in the array.

Remarks

ObjectAcceptFormats contains a zero-based array of strings, which describes 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 container control doesn't contain an object, an error occurs when you attempt to access this property.


ObjectAcceptFormats Property Applies To

OLE Container Control


ObjectAcceptFormats Property See Also
See Also

Data Property

DataText Property

Format Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


ObjectAcceptFormatsCount Property

See Also	Example 	Applies To

Returns the number of formats that can be accepted by an object.

Syntax

object.ObjectAcceptFormatsCount

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

Use this property to get the number of elements in the ObjectAcceptFormats property array.


ObjectAcceptFormatsCount Property Applies To

OLE Container Control


ObjectAcceptFormatsCount Property See Also
See Also

Data Property

DataText Property

Format Property

ObjectAcceptFormats Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


DisplayType Property

See Also	Applies To

Returns or sets a value indicating whether an object displays its contents or an icon.

Syntax

object.DisplayType [ = value]

The DisplayType property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer or constant specifying whether an object displays its contents or an icon, as described in Settings.

Settings

The settings for value are:

Constant	Value	Descriptioni

vbOLEDisplayContent	0	(Default) Content.  When the OLE container control contains an object, the object's data is displayed in the control.

vbOLEDisplayIcon	1	Icon.  When the OLE container control contains an object, the object's icon is displayed in the control.

Remarks

This property determines the default setting of the Display As Icon check box in the Insert Object and Paste Special dialog boxes.  When you display these dialog boxes either at run time (with the InsertObjDlg or PasteSpecialDlg methods) or design time, the Display As Icon check box is automatically selected if this property is set to 1 (Icon).

When creating an object at run time using the CreateEmbed or CreateLink methods, use the DisplayType property to determine if the object is displayed as an icon (set DisplayType = 1) or if the object's data is displayed in the control (set DisplayType = 0).

Once you create an object, you can't change its display type.


DisplayType Property See Also
See Also

CreateEmbed Method

CreateLink Method

InsertObjDlg Method

PasteSpecialDlg Method


DisplayType Property Applies To

OLE Container Control


ObjectGetFormats Property

See Also	Example 	Applies To

Returns the list of formats an object can provide.

Syntax

object.ObjectGetFormats(number)

The ObjectGetFormats property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression indicating the element in the array.

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.


ObjectGetFormats Property Applies To

OLE Container Control


ObjectGetFormats Property See Also
See Also

Data Property

DataText Property

Format Property

ObjectAcceptFormats Property

ObjectGetFormatsCount Property


ObjectGetFormatsCount Property

See Also	Example 	Applies To

Returns the number of formats an object can provide.

Syntax

object.ObjectGetFormatsCount

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

Use this property to determine the number of elements in the ObjectGetFormats property array.


ObjectGetFormatsCount Property Applies To

OLE Container Control


ObjectGetFormatsCount Property See Also
See Also

Data Property

DataText Property

Format Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property


OLEType Property

See Also	Applies To

Returns the status of the object in an OLE container control.

Syntax

object.OLEType

The object is an object expression that evaluates to an object in the Applies To list.

Return Values

The OLEType property returns the following values:

Constant	Value	Description

vbOLELinked	0	Linked.  The OLE container control contains a linked object.  All the object's data is managed by the application that created it.  When the object is saved using the SaveToFile method, only link information such as SourceDoc, SourceItem, and so on is saved in the specified file by your Visual Basic application.

vbOLEEmbedded	1	Embedded.  The OLE container control contains an embedded object.  All the object's data is managed within the Visual Basic application.  When the object is saved using the SaveToFile method, all data associated with the object is saved in the specified file.

vbOLENone	3	None.  The OLE container control doesn't contain an object.

Remarks

Use this property to determine if the OLE container control contains an object or to determine the type of object the OLE container 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.


OLEType Property Applies To

OLE Container Control


OleType Property See Also
See Also

AppIsRunning Property

FileNumber Property

OLETypeAllowed Property

SaveToFile Method


ObjectVerbs Property

See Also	Example 	Applies To

Returns the list of verbs an object supports.

Syntax

object.ObjectVerbs(number)

The ObjectVerbs property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression indicating the element in the array.

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 to determine an action to perform when an object is activated with the DoVerb method.  The list of verbs in the array varies from object to object and depends on the current conditions.

Each object can support its own set of verbs.  The following values represent standard verbs 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 activation, the object is activated within the OLE container control.

-2	Opens the object in a separate application window.  If the application that created the object supports in-place activation, the object is activated in its own window.

-3	For embedded objects, hides the application that created the object.

-4	If the object supports in-place activation, activates the object for in-place activation and shows any user interface tools.  If the object doesn't support in-place activation, the object doesn't activate, and an error occurs.

-5	If the user moves the focus to the OLE container control, creates a window for the object and prepares the object to be edited.  An error occurs if the object doesn't support activation on a single mouse click.

-6	Used when the object is activated for editing to discard all record of changes that the object's application can undo.

Note   These verbs may not be listed in the ObjectVerbs property array.

The first verb in the ObjectVerbs array, ObjectVerbs(0), is the default verb.  Unless otherwise specified, this verb activates the object.

The remaining verbs in the array can be displayed on a menu.  If it's appropriate to display the default verb in a menu, the default verb has two entries in the ObjectVerbs array.

Applications that display objects typically include an Object command on the Edit menu.  When the user chooses Edit Object, a 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, use the FetchVerbs method.  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.


ObjectVerbs Property Applies To

OLE Container Control


ObjectVerbs Property See Also
See Also

AutoVerbMenu Property

DoVerb Method

FetchVerbs Method

ObjectVerbFlags Property

ObjectVerbsCount Property

Verb Property


ObjectVerbsCount Property

See Also	Example 	Applies To

Returns the number of verbs supported by an object.

Syntax

object.ObjectVerbsCount

The object is an object expression that evaluates to an OLE container control.

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, use the FetchVerbs method.


ObjectVerbsCount Property Applies To

OLE Container Control


ObjectVerbsCount Property See Also
See Also

FetchVerbs Method

ObjectVerbFlags Property

ObjectVerbs Property

Verb Property


SourceDoc Property

See Also	Applies To

Returns or sets the filename to use when you create an object.

Note   You set the SourceDoc property for compatibility with the Action property in earlier versions.  For current functionality, use the CreateEmbed and CreateLink methods.

Syntax

object.SourceDoc [ = name]

The SourceDoc property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

name	A string expression specifying a filename.

Remarks

Use the SourceDoc property to specify the file to be linked when creating a linked object using the Action property.  Use the SourceItem property to specify data within the file to be linked.

When creating an embedded object using the Action property, if the SourceDoc property is set to a valid filename, 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 a zero-length 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"


SourceDoc Property Applies To

OLE Container Control


SourceDoc Property See Also
See Also

Action Property (OLE Container)

Class Property

CreateEmbed Method

CreateLink Method

OLEType Property

OLETypeAllowed Property

SourceItem Property


SourceItem Property

See Also	Applies To

Returns or sets the data within the file to be linked when you create a linked object.

Syntax

object.SourceItem [ = string]

The SourceItem property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying the data to be linked.

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, 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 container 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 contains 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 a zero-length 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"


SourceItem Property Applies To

OLE Container Control


SourceItem Property See Also
See Also

Class Property

OLEType Property

OLETypeAllowed Property

SourceDoc Property


AppIsRunning Property

See Also	Applies To

Returns or sets a value that indicates whether the application that created the object in the OLE container control is running.  Not available at design time.

Syntax

object.AppIsRunning [= boolean]

The AppIsRunning property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether or not the application that produced the object in the OLE container control is running, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The application that produced the object in the OLE container control is running.

False	The application that produced the object in the OLE container control isn't running.

Remarks

You can set the value of the AppIsRunning property to start the application that produces the object in the OLE container control.  Doing this causes objects to activate more rapidly.  You can also set this property to False to close the application when the object loses the focus.


AppsIsRunning See Also
See Also

OLEType Property


AppsIsRunning Applies To
AppIsRunning Property Applies To

OLE Container Control


UpdateOptions Property

See Also	Applies To

Returns or sets a value specifying how an object is updated when linked data is modified.

Syntax

object.UpdateOptions [ = number]

The UpdateOptions property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A integer specifying how an object is updated, as described in Settings.

Settings

The settings for number are:

Constant	Value	Description

vbOLEAutomatic	0	(Default) Automatic.  The object is updated each time the linked data changes.

vbOLEFrozen	1	Frozen.  The object is updated whenever the user saves the linked data from within the application in which it was created.

vbOLEManual	2	Manual.  The object is updated only by using the Update method.

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.


UpdateOptions Property Applies To

OLE Container Control


UpdateOptions Property See Also
See Also

Class Property

OLEType Property

OLETypeAllowed Property

Update Method (OLE Container)

Updated Event


Verb Property

See Also	Applies To

Returns or sets a value specifying an operation to perform when an object is activated using the Action property.

Note   The Verb property is included for compatibility with the Action property in earlier versions.  For current functionality, use the DoVerb method.

Syntax

object.Verb [= number]

The Verb property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A value that specifies the operation to perform.

Remarks

Each object can support its own set of verbs.  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.

Set AutoActivate to 2 (Double-Click) to automatically activate an object when it's 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.


Verb Property Applies To

OLE Container Control


Verb Property See Also
See Also

Action Property (OLE Container)

AutoActivate Property

AutoVerbMenu Property

DoVerb Method

ObjectVerbs Property

ObjectVerbsCount Property

OLEType Property

OLETypeAllowed Property


Updated Event

See Also	Applies To

Occurs when an object's data has been modified.

Syntax

Sub object_Updated (code As Integer)

The Updated event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

code	An integer that specifies how the object was updated, as described in Settings.

Settings

The settings for code are:

Constant	Value	Description

vbOLEChanged	0	The object's data has changed.

vbOLESaved	1	The object's data has been saved by the application that created the object.

vbOLEClosed	2	The file containing the linked object's data has been closed by the application that created the object.

vbOLERenamed	3	The file containing the linked object's data has been renamed by the application that created the object.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.  You can use this event to determine 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 that the object needs to be saved.  After you save the object, reset the variable.


Updated Event Applies To

OLE Container Control


Update Event See Also
See Also

Class Property

OLEType Property

OLETypeAllowed Property

UpdateOptions Property


AutoActivate Property

See Also	Applies To

Returns or sets a value that enables the user to activate an object by double-clicking the OLE container control or by moving the focus to the OLE container control.

Syntax

object.AutoActivate [= value]

The AutoActivate property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer or constant specifying the technique used to activate the object within the OLE container control, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbOLEActivateManual	0	Manual.  The object isn't automatically activated.  You can activate an object programmatically using the DoVerb method.

vbOLEActivateGetFocus	1	Focus.  If the OLE container control contains an object that supports single click activation, the application that provides the object is activated when the OLE container control receives the focus.

vbOLEActivateDoubleclick	2	(Default) Double-Click.  If the OLE container control contains an object, the application that provides the object is activated when the user double-clicks the OLE container control or presses ENTER when the control has the focus.

vbOLEActivateAuto	3	Automatic.  If the OLE container control contains an object, the application that provides the object is activated based on the object's normal method of activation [image] either when the control receives the focus or when the user double-clicks the control.

Remarks

You can determine if the OLE container control contains an object by checking the OLEType property.

Note   When AutoActivate is set to 2 (Double-Click), the DblClick event doesn't occur when the user double-clicks an OLE container control.


AutoActivate Property Applies To

OLE Container Control


AutoActivate Property See Also
See Also

DoVerb Method

OLEType Property


AutoVerbMenu Property

See Also	Applies To

Returns or sets a value that determines if a pop-up menu containing the object's verbs is displayed when the user clicks the OLE container control with the right mouse button.

Syntax

object.AutoVerbMenu[ = boolean]

The AutoVerbMenu property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether a pop-up menu is displayed, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) When the user clicks the OLE container 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 don't occur when the OLE container control is clicked with the right mouse button.


AutoVerbMenu See Also
See Also

ObjectVerbs Property

ObjectVerbsCount Property

Verb Property


AutoVerbMenu Property Applies To

OLE Container Control


Object Property (OLE Container)

See Also	Applies To

Returns the object and/or a setting of an object's method or property in an OLE container control.

Syntax

object.Object[.property | .method]

The Object property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

property	Property that the object supports.

method	Method that the object supports.

Remarks

Use this property to specify an object you want to use in an OLE Automation task.

You use the object returned by the Object property in an OLE Automation task by using the properties and methods of that object.  For information on which properties and methods an object supports, see the documentation for the application that created the object.


Object Property Applies To

OLE Container Control


Object Property See Also
See Also

CreateObject Function

GetObject Function

OLE Automation


OLETypeAllowed Property

See Also	Applies To

Returns or sets the type of object the OLE container control can contain.

Syntax

object.OLETypeAllowed [ = value]

The OLETypeAllowed property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer or constant that specifies the type of object, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbOLELinked	0	Linked.  The OLE container control can contain only a linked object.

vbOLEEmbedded	1	Embedded.  The OLE container control can contain only an embedded object.

vbOLEEither	2	(Default) Either.  The OLE container control can contain either a linked or an embedded object.

Remarks

This property determines the type of object a user can create:

When using the Insert Object dialog box, use the InsertObjDlg method to display this dialog box.

When using the Paste Special dialog box, use the PasteSpecialDlg method to display this dialog box.

When pasting an object from the system Clipboard, use the Paste method to paste objects from the system Clipboard.

Use the OLEType property to determine an object's type (linked, embedded, or none).


OLETypeAllowed Property Applies To

OLE Container Control


OleTypeAllowed Property See Also
See Also

AppIsRunning Property

InsertObjDlg Method

OLEType Property

Paste Method

PasteSpecialDlg Method


PasteSpecialDlg Method

See Also	Applies To

Displays the Paste Special dialog box.

Syntax

object.PasteSpecialDlg

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

At run time, you display this dialog box to enable the user to paste an object from the system Clipboard.  This dialog box 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, or either) using this dialog box.

If the PasteOK property setting is True and Visual Basic can't paste the object, the OLE container control deletes any object already in the control.


PasteSpecialDlg Method See Also
See Also

OLETypeAllowed Property


PasteSpecialDlg Method Applies To

OLE Container Control


Copy Method

See Also	Applies To

Copies the object within an OLE container control to the system Clipboard.

Syntax

object.Copy

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

When you copy an object onto the system Clipboard, all the data and link information associated with the object is placed on the system Clipboard.  You can copy both linked and embedded objects onto the system Clipboard.

You can use this method to support an Edit Copy command on a menu.


Copy Method See Also
See Also

Paste Method


Copy Method Applies To

OLE Container Control


CreateEmbed Method

See Also	Applies To

Creates an embedded object.  Doesn't support named arguments.

Syntax

object.CreateEmbed sourcedoc, class

The CreateEmbed method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

sourcedoc	Required.  The filename of a document used as a template for the embedded object.  Must be a zero-length string ("") if you don't specify a source document.

class	Optional.  The name of the class of the embedded object.  Ignored if you specify a filename for sourcedoc.

Remarks

To view a list of valid class names available on your system, select the Class property in the Properties window, and click the Properties button.

Note   You don't need to set the Class and SourceDoc properties when using the CreateEmbed method to create an embedded object.

When you create a new object, the application associated with the class name (for example, EXCEL.EXE) must be correctly registered with the operating system.  (The application setup program should register the application correctly.)


Copy Method See Also
See Also

Class Property

OLETypeAllowed Property


Copy Method Applies To
CreateEmbed Method Applies To

OLE Container Control


CreateLink Method

See Also	Applies To

Creates a linked object from the contents of a file.  Doesn't support named arguments.

Syntax

object.CreateLink sourcedoc, sourceitem

The CreateLink method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

sourcedoc	Required.  The file from which the object is created.

sourceitem	Optional.  The data within the file to be linked in the linked object.

Remarks

If you specify values for the arguments of this method, those values override the settings of the SourceDoc and SourceItem properties.  Those properties are updated to reflect the argument values when the method is invoked.

When an object is created with this method, the OLE container control displays an image of the file specified by the SourceDoc property.  If the object is saved, only the link references are saved because the OLE container control contains only a metafile image of the data and no actual source data.

When you create a new object, the application associated with the class name (for example, EXCEL.EXE) must be correctly registered with the operating system.  (The application setup program should register the application correctly.)


CreateLink Method See Also
See Also

CreateEmbed Method

OLETypeAllowed Property

SourceDoc Property

SourceItem Property


CreateLink Method Applies To

OLE Container Control


Delete Method (OLE Container)

Applies To

Deletes the specified object and frees the memory associated with it.

Syntax

object.Delete

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

This method enables you to explicitly delete an object.  Objects are automatically deleted when a form is closed or when the object is replaced with a new object.


Delete Method (OLE Container) Applies To
Delete Method Applies To

OLE Container Control


InsertObjDlg Method

See Also	Applies To

Displays the Insert Object dialog box.

Syntax

object.InsertObjDlg

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

At run time, you display this dialog box to enable the user to create a linked or embedded object by choosing the type of object (linked or embedded) and the application provides the object.

Use the OLETypeAllowed property to determine the type of object that can be created (linked, embedded, or either) using this dialog box.

When you create a new object, the application associated with the class name (for example, EXCEL.EXE) must be correctly registered with the operating system.  (The application setup program should register the application correctly.)


InsertObjDlg Method See Also
See Also

OLETypeAllowed Property


InsertObjDlg Method Applies To

OLE Container Control


Paste Method

See Also	Applies To

Copies data from the system Clipboard to an OLE container control.

Syntax

object.Paste

The object is an object expression that evaluates to an object in the Applies To list

Remarks

To use this method, set the OLETypeAllowed property, and then check the value of the PasteOK property.  You can't paste successfully unless PasteOK returns a value of True.

If the Paste method was carried out, the OLEType property is set to vbOLELinked (0) or vbOLEEmbedded (1).  If the Paste method wasn't carried out, the OLEType property is set to vbOLENone (3).

You can use this method to support an Edit Paste command on a menu.

If the PasteOK property setting is True and Visual Basic can't paste the object, the OLE container control deletes any object already in the control.


Paste Method See Also
See Also

OLEType Property

OLETypeAllowed Property

PasteOK Property


Paste Method Applies To

OLE Container Control


ReadFromFile Method

See Also	Applies To

Loads an object from a data file created using the SaveToFile method.  Doesn't support named arguments.

Syntax

object.ReadFromFile filenumber

The ReadFromFile method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filenumber	Required.  A numeric expression specifying the file number used when loading an object.  This number must correspond to an open, binary file.

Remarks

You can save an object to a data file using the SaveToFile or SaveToOle1File methods.


ReadFromFile Method See Also
See Also

SaveToFile Method

SaveToOle1File Method


ReadFromFile Method Applies To

OLE Container Control


SaveToFile Method

See Also	Applies To

Saves an object to a data file.  Doesn't support named arguments.

Syntax

object.SaveToFile filenumber

The SaveToFile method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filenumber	Required.  A numeric expression specifying the file number used when saving an object.  This number must correspond to an open, binary file.

Remarks

Use this method to save OLE objects.  To save an OLE object, use the SaveToOle1File method.

If the object is linked (OLEType = vbOLELinked, 0), 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 object is embedded (OLEType = vbOLEEmbedded, 1), the object's data is maintained by the OLE container control and can be saved by your Visual Basic application.

You can load an object saved to a data file with the ReadFromFile method.


SaveToFile Method See Also
See Also

OLEType Property

ReadFromFile Method

SaveToOle1File Method


SaveToFile Method Applies To

OLE Container Control


DoVerb Method

See Also	Applies To

Opens an object for an operation, such as editing. Doesn't support named arguments.

Syntax

object.DoVerb (verb)

The DoVerb method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

verb	Optional.  The verb to execute of the object within the OLE container control.  If not specified, the default verb is executed.  The value of this argument can be one of the standard verbs supported by all objects or an index of the ObjectVerbs property array.

Remarks

If you set the AutoActivate property to 2 (Double-Click), the OLE container control automatically activates the current object when the user double-clicks the control.

Each object can support its own set of verbs.  The following values represent standard verbs every object should support:

Constant	Value	Description

vbOLEPrimary	0	The default action for the object.

vbOLEShow	-1	Activates the object for editing.  If the application that created the object supports in-place activation, the object is activated within the OLE container control.

vbOLEOpen	-2	Opens the object in a separate application window.  If the application that created the object supports in-place activation, the object is activated in its own window.

vbOLEHide	-3	For embedded objects, hides the application that created the object.

vbOLEUIActivate	-4	If the object supports in-place activation, activates the object for in-place activation and shows any user interface tools.  If the object doesn't support in-place activation, the object doesn't activate, and an error occurs.

vbOLEInPlaceActivate	-5	If the user moves the focus to the OLE container control, creates a window for the object and prepares the object to be edited.  An error occurs if the object doesn't support activation on a single mouse click.

vbOLEDiscardUndoState	-6	Used when the object is activated for editing to discard all record of changes that the object's application can undo.

Note   These verbs may not be listed in the ObjectVerbs property array.


DoVerb Method See Also
See Also

AutoActivate Property

ObjectVerbs Property

Verb Property


DoVerb Method Applies To

OLE Container Control


FetchVerbs Method

See Also	Applies To

Updates the list of verbs an object supports.

Syntax

object.FetchVerbs

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

You can read the updated list of verbs using the ObjectVerbs property.


Fetch Method See Also
See Also

AutoVerbMenu Property

DoVerb Method

ObjectVerbs Property

ObjectVerbsCount Property


Fetch Method Applies To
FetchVerbs Method Applies To

OLE Container Control


Close Method (OLE Container)

Applies To

Closes an object and terminates the connection to the application that provided the object.

Syntax

object.Close

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

This method applies only to embedded objects and is equivalent to closing the object.  It has no effect on linked objects.


Close Method (OLE Container) Applies To

OLE Container Control


Update Method (OLE Container)

Applies To

Retrieves the current data from the application that supplied the object and displays that data as a graphic in the OLE container control.

Syntax

object.Update

The object is an object expression that evaluates to an object in the Applies To list.


Update Method (OLE Container) Applies To

OLE Container Control


Action Property (OLE Container)

See Also	Applies To

Sets a value that determines an action.  Not available at design time.

Note   The Action property is included for compatibility with earlier versions.  For current functionality, use the methods listed in Settings.

Syntax

object.Action = value

The Action property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or integer specifying the type of action, as described in Settings.

Settings

The settings for value are:

Value	Description	Current method
0	Creates an embedded object.	CreateEmbed
1	Creates a linked object from the contents of a file.	CreateLink
4	Copies the object to the system Clipboard.	Copy
5	Copies data from the system Clipboard to an OLE container control.	Paste
6	Retrieves the current data from the application that supplied the object and displays that data as a picture in the OLE container control.	Update
7	Opens an object for an operation, such as editing.	DoVerb
9	Closes an object and terminates the connection to the application that provided the object.	Close
10	Deletes the specified object and frees the memory associated with it.	Delete
11	Saves an object to a data file.	SaveToFile
12	Loads an object that was saved to a data file.	ReadFromFile
14	Displays the Insert Object dialog box.	InsertObjDlg
15	Displays the Paste Special dialog box.	PasteSpecialDlg
17	Updates the list of verbs an object supports.	FetchVerbs
18	Saves an object to the OLE file format.	SaveToOle1File


Action Property (OLE Container) Applies To

OLE Container Control


Action Property (OLE Container) See Also
See Also

Close Method (OLE Container)

Copy Method

CreateEmbed Method

CreateLink Method

Delete Method (OLE Container)

DoVerb Method

FetchVerbs Method

InsertObjDlg Method

Paste Method

PasteSpecialDlg Method

ReadFromFile Method

SaveToFile Method

SaveToOle1File Method

Update Method (OLE Container)


MiscFlags Property

See Also	Applies To

Returns or sets a value that determines access to one or more additional features of the OLE container control.

Syntax

object.MiscFlags [ = value]

The MiscFlags property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer or constant specifying access to an additional feature, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbOLEMiscFlagMemStorage	1	Causes the control to use memory to store the object while it's loaded.

vbOLEMiscFlagDisableInPlace	2	Overrides the control's default behavior of allowing in-place activation for objects that support it.

Remarks

The vbOLEMiscFlagMemStorage flag setting is faster than the object's default action, which is to store it on disk as a temporary file.  This setting can, however, use 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 activation, you can use the vbOLEMiscFlagDisableInPlace 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 = vbOLEMiscFlagMemStorage Or vbOLEMiscFlagDisableInPlace


MiscFlags Property Applies To

OLE Container Control


MiscFlags Property See Also
See Also

And Operator

Or Operator


SaveToOle1File Method

See Also	Applies To

Saves an object in the OLE file format. Doesn't support named arguments.

Syntax

object.SaveToOle1File filenumber

The SaveToOle1File method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filenumber	Required.  A numeric expression specifying the file number used when saving or loading an object.  This number must correspond to an open, binary file.

Remarks

If the object is linked (OLEType = vbOLELinked, 0), 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 object is embedded (OLEType = vbOLEEmbedded, 1), the object's data is maintained by the OLE container control and can be saved by your Visual Basic application.

If the object you want to save is an OLE object, use the SaveToFile method.


SaveToOle1File Method See Also
See Also

ReadFromFile Method

SaveToFile Method


SaveToOle1File Method Applies To

OLE Container Control


Format Property

See Also	Applies To

Returns or sets the format when sending data to and getting data from an application that created an object.  Not available at design time.

Syntax

object.Format [ = format]

The Format property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

format	A string expression specifying the format used with the Data and DataText properties.

Remarks

Use the ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, and ObjectGetFormatsCount properties to get a list of the acceptable data formats for a specific class of object.

Many applications that provide objects support only one or two formats.  For example, Microsoft Draw accepts only the CF_METAFILEPICT format.  Although CF_METAFILEPICT resembles the intrinsic constant vbCFMetafile (numeric value 3) defined in the Visual Basic (VB) object library in the Object Browser, it's actually a string literal and is 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).


Format Property See Also
See Also

Data Property

DataText Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


Format Property Applies To

OLE Container Control


PasteOK Property

See Also	Example	Applies To

Returns a value that determines whether the contents of the system Clipboard can be pasted into the OLE container control.

Syntax

object.PasteOK

The object is an object expression that evaluates to an object in the Applies To list.

Remarks

When this property setting is True, you can paste the contents of the system Clipboard into the OLE container control.

Use the OLETypeAllowed property to specify the type of object (linked or embedded) you want to paste into the OLE container control.  Once you successfully paste an object into the OLE container control, you can check the OLEType property setting to determine the type of object that was created.

You can use this property if your application supports a Paste command on an Edit menu.  If PasteOK is False, disable the menu command; otherwise, it can be enabled.  Enable and disable menu commands by setting their Enabled property to True or False, respectively.

You paste an object into the OLE container control with the Paste method.

To provide more flexibility to the user, display a Paste Special dialog box when the user chooses the Edit Paste command.  (Set OLETypeAllowed = 2, and then use the PasteSpecialDlg method.)  When this dialog box is displayed, an object is pasted onto the system Clipboard based on the user's selections in the dialog box.


PasteOK Property See Also
See Also

Enabled Property

OLEType Property

OLETypeAllowed Property

Paste Method

PasteSpecialDlg Method


PasteOK Property Applies To

OLE Container Control


DataText Property Example

This example sends data to the Microsoft Graph application, so you must have Graph installed on your system to run the example.  Create a form about one-half the size of the screen with a CommandButton control (Command1) in the upper-left corner of the form and an OLE container control (OLE1) placed below the CommandButton.

When you place the OLE container control on the form, the Insert Object dialog box is displayed.  Choose Cancel and press F5 to run the example.

Private 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 using the DataText property.

' Activate MSGRAPH as hidden.

Ole1.DoVerb - 3

If Ole1.AppIsRunning Then

Ole1.DataText = Msg

' Update the object.

Ole1.Update

Else

MsgBox "Graph isn't active."

End If

End Sub

Sub Form_Load ()

Ole1.Format = "CF_TEXT"	' Set the file format to text.

Ole1.SizeMode = 2	' Autosize.

Ole1.CreateEmbed "", "MSGRAPH"

End Sub


ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, ObjectGetFormatsCount, ObjectVerbs, ObjectVerbsCount Properties
ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, ObjectGetFormatsCount, ObjectVerbs, ObjectVerbsCount Properties Example

To run this example, place an OLE container control and three ListBox controls on a form.  Paste the example code into the Declarations section of the form and press F5.  When the Insert Object dialog box is displayed, select an application in the New Object list box and choose OK to create an object.

Private Sub Form_Click ()

Dim I	' Declare variable.

' Display the Insert Object dialog box.

Ole1.InsertObjDlg

' Update the list of available verbs.

Ole1.FetchVerbs	' Fetch verbs.

' Clear the list boxes.

List1.Clear

List2.Clear

List3.Clear

' Fill the verbs list box. Because 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


PasteOK Property Example

This example pastes an object in the OLE container control if the PasteOK property setting is True.  Otherwise, the example displays a message box.

Private Sub mnuEditPaste_Click ()

' Check value of PasteOK.

If Ole1.PasteOK Then

Ole1.Paste	' Enable Paste command if True.

Else	' Otherwise, disable Paste

mnuEditPaste.Enabled = False	' menu command and give

MsgBox "Can't paste."	' appropriate message.

End If

End Sub


ObjectMove Event

See Also	Applies To

Occurs immediately after the object within an OLE container control is moved or resized while the object is active.

Syntax

Private Sub object_ObjectMove(left As Single, top As Single, width As Single, height As Single)

The ObjectMove event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

left	The coordinate of the left edge of the OLE container control immediately after it's moved or resized.

top	The coordinate of the top edge of the OLE container control immediately after it's moved or resized.

width	The width of the OLE container control immediately after it's moved or resized.

height	The height of the OLE container control immediately after it's moved or resized.

Remarks

When a user moves or resizes an OLE container control, your application can use the ObjectMove event to determine whether to actually change the size and position of the control.  If the ObjectMove event procedure doesn't change the OLE container control's position or size, the object within the OLE container control returns to its original position and is informed of its new size.  The coordinates passed as arguments to this event include the border of the OLE container control.

The ObjectMove and Resize events are triggered when the OLE container control receives information about the size of the object it contains.  However, the Resize event doesn't receive any information about the position of the control.  If the OLE container control is moved off the form, the arguments have negative or positive values that represent the position of the object relative to the top and left of the form.


ObjectMove Event See Also
 See Also

DragMode Property

Move Method

Resize Event

SizeMode Property


ObjectMove Event Applies To

OLE Container Control


OLEDropAllowed Property

See Also	Applies To

Returns or sets a value that determines whether an OLE container control can be a drop target for OLE drag-and-drop operations.

Syntax

object.OLEDropAllowed [= boolean]

The OLEDropAllowed property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the OLE container control can be a drop target, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	When dragging an object that can be linked or embedded, a drop icon appears when the mouse pointer moves over the OLE container control.  Dropping the object on the OLE container control has the same effect as pasting the object from the system Clipboard using the Paste method.

False	(Default) No drop icon appears over the OLE container control when dragging an object that can be linked or embedded.  Dropping the object on the OLE container control has no effect on the control.

Remarks

The MousePointer property determines the shape of the mouse pointer when the OLEDropAllowed property is set to True.  If the setting of the MousePointer property is 0 (Default), Visual Basic displays the standard drag-and-drop icon for the action taking place.

The setting of the OLETypeAllowed property must be 1 (vbOLEEmbedded) or 2 (vbOLEEither) to move or copy the object that can be linked or embedded and 0 (vbOLELinked) or 2 to link the object.  Dropping an object when OLEDropAllowed is set to True has the same effect on the Class, SourceDoc, and SourceItem property settings as using the Paste method of the OLE container control.

If the OLEDropAllowed property is set to True, the OLE container control doesn't receive DragDrop or DragOver events when dragging an object.  Also, the setting of the DragMode property has no effect on the drag-and-drop behavior of the OLE container control when the OLEDropAllowed property is set to True.


OLEDropAllowed Property See Also
 See Also

Class Property

DragMode Property

OLETypeAllowed Property

Paste Method

SourceDoc Property

SourceItem Property


OLEDropAllowed Property Applies To

OLE Container Control


ClassModule Object

See Also	Properties	Events

A ClassModule object contains properties that govern the behavior of a class as well as the code that defines properties and methods of the class.

Remarks

You use a ClassModule as a container for the code that defines the properties and methods of a class you create.  A ClassModule defines only one class; however, you can have more than one ClassModule in a project.  A ClassModule behaves very much like a form, but without a visible interface of its own.

You can create instances of a class defined in a ClassModule.  For example, you can use Dim MyInstance As New MyClass, where MyClass is the name of the ClassModule.  You can only create a ClassModule at design time by choosing the Class Module command from the Insert menu.

After you create a ClassModule, the code you write in that module defines the properties and methods of that class.  You can also set the properties of the ClassModule itself to further define the behavior of the class:

The Instancing property determines if applications outside your project can declare new instances of your class.

The Public property determines if other applications can write code to invoke the properties and methods of your class.

The Name property determines the name of the class.


ClassModule Object See Also
 See Also

Form Object, Forms Collection


ClassModule Object Properties

Instancing Property

Name Property

Public Property


ClassModule Object Events

Initialize Event

Terminate Event


Instancing Property

See Also	Applies To

Sets a value that specifies whether you can create instances of a public class outside a project.  Not available at run time.

Settings

The Instancing property has these settings:

Setting	Description

0	(Default)  Not Creatable.  You can create instances of the class inside the project only.

1	Creatable SingleUse.  You can create instances of the class both inside and outside the project.  Each request for an instance of the class by an OLE client outside the project causes a separate copy of the OLE server to be started.

2	Creatable MultiUse.  You can create instances of the class both inside and outside the project.  Requests for an instance of the class by an OLE client outside the project will be supplied by an already running copy of the OLE server, if any.  If there are no copies of the OLE server running, a copy is started to supply the class.

Remarks

When a class is creatable, you can use any of the following techniques to create instances of the class from other applications:

Use the CreateObject function, as in:

Set MyInstance = CreateObject("MyProject.MyClass")

Use the Dim statement within the same project (or outside the project if the Public property is also set to True), as in:

Dim MyInstance As New MyClass

If the Public property is False, the setting of the Instancing property is ignored.  You can always create instances of the class within the project that defines the class.  If the Public property is True, the class is visible and therefore can be controlled by other applications once an instance of the class exists.


Creatable Property See Also
 See Also

CreateObject Function

Dim Statement

Public Property


Creatable Property Applies To
Instancing Property Applies To

ClassModule Object


Description Property (ClassModule)

Applies To

Sets the text displayed in the Object Browser when a class is selected.  Not available at run time.

Settings

The Description property is a string value that describes the purpose of the class when it's selected in the Object Browser.  The default value of this property is a zero-length string ("").

To set the Description property, select the project and class in the Object Browser, and then click the Options button.  When the Member Options dialog box is displayed, enter the value of the Description property in the Description text box.

Remarks

Once set, this property enables other users to use the Object Browser to find out about the properties and methods of the classes provided by your compiled OLE server.

The Description property is different than the Application Description string you can enter in the Project Options dialog box.  The Application Description string determines the description of the OLE server in the References dialog box.  The Description property determines the description of the class and of the properties and methods of your class in the Object Browser.


Description Property Applies To

ClassModule Object


Public Property

See Also	Applies To

Sets a value that specifies whether a class you create is visible outside the project.  Not available at run time.

Settings

The Public property has these settings:

Setting	Description

True	The class you create is visible both within the project and by applications outside the project.

False	(Default) The class you create is visible only within the project.

Remarks

You can use the Public and Instancing properties together to determine how classes you define are exposed to other applications.  The following table summarizes how the settings of these two properties affect the visibility and creatability of a class:

Public	Instancing	Result

False	N/A	The class is creatable only within the project that defines the class.  The class isn't visible to other applications.

True	0	The class is creatable only within the project that defines the class.  The class is visible and therefore can be controlled by other applications once an instance of the class exists.

True	1	You can create instances of the class both inside and outside the project.  Each request for an instance of the class by an OLE client outside the project causes a separate copy of the OLE server to be started.  The class is visible and therefore can be controlled by other applications once an instance of the class exists.

True	2	You can create instances of the class both inside and outside the project.  Requests for an instance of the class by an OLE client outside the project will be supplied by an already running copy of the OLE server, if any.  If there are no copies of the OLE server running, a copy is started to supply the class.  The class is visible and therefore can be controlled by other applications once an instance of the class exists.


Public Property See Also
 See Also

Instancing Property


Public Property Applies To

ClassModule Object


Initialize Event

See Also	Applies To

Occurs when an application creates an instance of a Form, MDIForm, or class.

Syntax

Private Sub object_Initialize( )

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

You trigger the Initialize event when you:

Use the CreateObject function to create an instance of a class.  For example:

Set X = CreateObject("Project1.MyClass")

Refer to a property or event of an automatically created instance of a form or class in your code.  For example:

MyForm.Caption = "Example"

Use this event to initialize any data used by the instance of the Form, MDIForm, or class.  For a Form or MDIForm, the Initialize event occurs before the Load event.


Initialize Event See Also
 See Also

CreateObject Function

Dim Statement

Load Event

Terminate Event


Initialize Event Applies To

ClassModule Object

Form Object, Forms Collection

MDIForm Object


Terminate Event

See Also	Applies To

Occurs when all references to an instance of a Form, MDIForm, or class are removed from memory by setting all the variables that refer to the object to Nothing or when the last reference to the object falls out of scope.

Syntax

Private Sub object_Terminate( )

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

For a Form or MDIForm, the Terminate event occurs after the Unload event.

The Terminate event isn't triggered if the instances of the form or class were removed from memory because the application terminated abnormally.  For example, if your application invokes the End statement before removing all existing instances of the class or form from memory, the Terminate event isn't triggered for that class or form.


Terminate Event See Also
 See Also

Initialize Event

QueryUnload Event

Set Statement

Unload Event


Terminate Event Applies To

ClassModule Object

Form Object, Forms Collection

MDIForm Object


Negotiate Property

See Also	Applies To

Sets a value that determines whether a control that can be aligned is displayed when an active object on the form displays one or more toolbars.  Not available at run time.

Settings

The Negotiate property has these settings:

Setting	Description

True	If the control is aligned within the form (the Align property is set to a nonzero value), the control remains visible when an active object on the form displays a toolbar.

False	(Default) The control isn't displayed when an active object on the form displays a toolbar.  The toolbar of the active object is displayed in place of the control.

Remarks

The Negotiate property exists for all controls with an Align property.  You use the Align property to align the control within a Form or MDIForm object; however, the toolbar negotiation occurs only on the MDIForm.  The aligned control must be on the MDIForm.

If the NegotiateToolbars property is set to False, the setting of the Negotiate property has no effect.


Negotiate Property See Also
 See Also

Align Property

NegotiateToolbars Property


Negotiate Property Applies To

Data Control

PictureBox Control


NegotiateMenus Property

See Also	Applies To

Sets a value that determines whether or not a form incorporates the menus from an object on the form on the form's menu bar.  Not available at run time.

Settings

The NegotiateMenus property has these settings:

Setting	Description

True	(Default) When an object on the form is active for editing, the menus of that object are displayed on the form's menu bar.

False	Menus of objects on the form aren't displayed on the form's menu bar.

Remarks

Using the NegotiateMenus property, you determine if the menu bar of a form will share (or negotiate) space with the menus of an active object on the form.  If you don't want to include the menus of the active object on the menu bar of your form, set NegotiateMenus to False.

You can't negotiate menus between an MDIForm object and an object on the MDIForm.

If NegotiateMenus is set to True, the form must have a menu bar defined, even if the menu bar isn't visible.  If the MDIChild property of the form is set to True, the menus of the active object are displayed on the menu bar of the MDI parent window (MDIForm object).

When NegotiateMenus is set to True, you can use the NegotiatePosition property of individual Menu controls to determine the menus that your form displays along with the menus of the active object.


NegotiateMenus Property See Also
 See Also

NegotiatePosition Property


NegotiateMenus Property Applies To

Form Object, Forms Collection


NegotiatePosition Property

See Also	Applies To

Sets a value that determines whether or not top-level Menu controls are displayed on the menu bar while a linked or embedded object on a form is active and displaying its menus.  Not available at run time.

Settings

The NegotiatePosition property has these settings:

Setting	Description

0	(Default) None.  The menu isn't displayed on the menu bar when the object is active.

1	Left.  The menu is displayed at the left end of the menu bar when the object is active.

2	Middle.  The menu is displayed in the middle of the menu bar when the object is active.

3	Right.  The menu is displayed at the right end of the menu bar when the object is active.

Remarks

Using the NegotiatePosition property, you determine the individual menus on the menu bar of your form that share (or negotiate) menu bar space with the menus of an active object on the form.  Any menu with NegotiatePosition set to a nonzero value is displayed on the menu bar of the form along with menus from the active object.

If the NegotiateMenus property is set to False, the setting of the NegotiatePosition property has no effect.


NegotiatePosition Property See Also
 See Also

NegotiateMenus Property


NegotiatePosition Property Applies To

Menu Control


NegotiateToolbars Property

See Also	Applies To

Sets a value that determines whether the toolbars of an object on an MDI child form are displayed on the MDIForm when the object on the MDI child form is active. Not available at run time.

Settings

The NegotiateToolbars property has these settings:

Setting	Description

True	(Default) The MDIForm object displays the toolbars of the active object on the top or bottom of the MDIForm.  The active object determines whether the toolbars are displayed at the top or bottom of the MDIForm.

False	The toolbars of the active object either aren't displayed at all or are displayed as floating tool palettes, as determined by the active object.

Remarks

Use the NegotiateToolbars property when creating a multiple-document interface (MDI) application that includes objects on MDI child forms.  With this property, you determine how the active object displays its toolbars.  By setting this property to True, the MDIForm shares (or negotiates) space at the top or bottom of the form to display the toolbars of the active object.

If the MDIForm also contains a toolbar, use the Negotiate property to determine how the various toolbars share the available space.


NegotiateToolbars Property See Also
 See Also

Negotiate Property


NegotiateToolbars Property Applies To

MDIForm Object


Action Property (CommonDialog)

See Also	Applies To

Returns or sets the type of dialog box to be displayed.  Not available at design time.

Note   The Action property is included for compatibility with earlier versions of Visual Basic.  For additional functionality, use the following new methods: ShowColor, ShowFont, ShowHelp, ShowOpen, ShowPrinter, and ShowSave.

Syntax

object.Action [= value]

The Action property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying the type of dialog box displayed, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	No Action.

1	Displays Open dialog box.

2	Displays Save As dialog box.

3	Displays Color dialog box.

4	Displays Font dialog box.

5	Displays Printer dialog box.

6	Runs WINHELP.EXE.


See Also

ShowColor Method

ShowFont Method

ShowHelp Method

ShowOpen Method

ShowPrinter Method

ShowSave Method


Action Property (CommonDialog) Applies To

CommonDialog Control


BackColor, ForeColor Properties

See Also	Example	Applies To

BackColor [image] returns or sets the background color of an object.

ForeColor [image] returns or sets the foreground color used to display text and graphics in an object.

Syntax

object.BackColor [= color]

object.ForeColor [= color]

The BackColor and ForeColor property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

color	A value or constant that determines the background or foreground colors of an object, as described in Settings.

Settings

Visual Basic uses the Microsoft Windows operating environment red-green-blue (RGB) color scheme.  The settings for color are:

Setting	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 by system color constants listed in the Visual Basic (VB) object library in the Object Browser.  The Windows operating environment substitutes the user's choices as specified in the Control Panel settings.

For all forms and controls, the default settings at design time are:

BackColor [image] set to the system default color specified by the constant vbWindowBackground.

ForeColor [image] set to the system default color specified by the constant vbWindowText.

Remarks

In the Label and Shape controls, the BackColor property is ignored if the BackStyle property setting is 0 (Transparent).

If you set the BackColor property on a Form object or a PictureBox control, all text and graphics, including the persistent graphics, are erased.  Setting the ForeColor property doesn't 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 3 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 isn't 0, Visual Basic uses the system colors, as defined in the user's Control Panel settings and by constants listed in the Visual Basic (VB) object library in the Object Browser.

To display text in the Windows operating environment, both the text and background colors must be solid.  If the text or background colors you've selected aren't 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

FillColor Property

FillStyle Property


BackColor, ForeColor Properties Apply To

CheckBox Control

Column Object

ComboBox Control

CommandButton Control (BackColor only)

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Label Control

ListBox Control

MDIForm Object (BackColor only)

OLE Container Control (BackColor only)

OptionButton Control

PictureBox Control

Printer Object (ForeColor only)

Shape Control (BackColor only)

TextBox Control


BackStyle Property

See Also	Applies To

Returns or sets a value indicating whether a Label control or the background of a Shape control is transparent or opaque.

Syntax

object.BackStyle [= number]

The BackStyle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying transparency, as described in Settings.

Settings

The settings for number are:

Setting	Description

0	Transparent [image] background color and any graphics are visible behind the control.

1	(Default) Opaque [image] the control's BackColor property setting fills the control and obscures any color or graphics behind it.

Remarks

You can use the BackStyle property to create transparent controls when you're using a background color on a Form object or PictureBox control or when you want to place a control over a graphic.  Use an opaque control when you want it to stand out.

A control's BackColor property is ignored if BackStyle = 0.


See Also

BackColor, ForeColor Properties


BackStyle Property Applies To

Label Control

OLE Container Control

Shape Control


BorderColor Property

See Also	Applies To

Returns or sets the color of an object's border.

Syntax

object.BorderColor [= color]

The BorderColor property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

color	A value or constant that determines the border color, as described in Settings.

Settings

Visual Basic uses the Microsoft Windows operating environment red-green-blue (RGB) color scheme.  The settings for color are:

Setting	Description

Normal RGB colors	Colors specified using the Color palette or by using the RGB or QBColor functions in code.

System default colors	Colors specified by system color constants listed in the Visual Basic (VB) object library in the Object Browser.  The system default color is specified by the vbWindowText constant.  The Windows operating environment substitutes the user's choices as specified in the Control Panel settings.

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 3 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 isn't 0, Visual Basic uses the system colors, as defined in the user's Control Panel settings and by constants listed in the Visual Basic (VB) object library in the Object Browser.


See Also

BackColor, ForeColor Properties

DrawWidth Property


BorderColor Property Applies To

Line Control

Shape Control


BorderStyle Property

See Also	Applies To

Returns or sets the border style for an object.  For the Form object and the TextBox control, read-only at run time.

Syntax

object.BorderStyle = [value]

The BorderStyleColor property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant that determines the border style, as described in Settings.

Settings

The BorderStyle property settings for a Form object are:

Setting	Description

0	None (no border or border-related 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 Dialog.  Can include Control-menu box and title bar; can't include Maximize or Minimize buttons.  Not resizable.

4	Fixed ToolWindow.  Under 16-bit versions of Windows and Windows NT 3.51 and earlier, behaves like Fixed Single.  Does not display Maximize or Minimize buttons.  Not resizable.  Under Windows 95, displays the Close button and displays the title bar text in a reduced font size.  The form does not appear in the Windows 95 task bar.

5	Sizable ToolWindow.  Under 16-bit versions of Windows and Windows NT 3.51 and earlier, behaves like Sizable.  Does not display Maximize or Minimize buttons.  Resizable.  Under Windows 95, displays the Close button and displays the title bar text in a reduced font size.  The form does not appear in the Windows 95 task bar.

The BorderStyle property settings for Grid, Image, Label, OLE container, PictureBox, and TextBox controls are:

Setting	Description

0	(Default for Image and Label controls) None.

1	(Default for Grid, PictureBox, TextBox, and OLE container controls) Fixed Single.

The BorderStyle property settings for Line and Shape controls 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.

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 Dialog) is useful for standard dialog boxes.  Settings 4 (Fixed ToolWindow) and 5 (Sizable ToolWindow) are useful for creating toolbox-style windows.

MDI child forms set to 2 (Sizable) are displayed within the MDI form in a default size defined by the Windows operating environment at run time.  For any other setting, the form is displayed in the size specified at design time.

Changing the setting of the BorderStyle property of a Form object may change the settings of the MinButton, MaxButton, and ShowInTaskbar properties.  When BorderStyle is set to 1 (Fixed Single) or 2 (Sizable), the MinButton, MaxButton, and ShowInTaskbar properties are automatically set to True.  When BorderStyle is set to 0 (None), 3 (Fixed Dialog), 4 (Fixed ToolWindow), or 5 (Sizable ToolWindow), the MinButton, MaxButton, and ShowInTaskbar properties are automatically set to False.

Note   If a form with a menu is set to 3 (Fixed Dialog), it is displayed with a setting 1 (Fixed Single) border instead.

At run time, a form is either modal or modeless, which you specify using the Show method.


 See Also

Caption Property

ControlBox Property

DrawStyle Property

MaxButton Property

MinButton Property

ShowInTaskbar Property


BorderStyle Property Applies To

Form Object

Grid Control

Image Control

Label Control

Line Control

OLE Container Control

PictureBox Control

Shape Control

TextBox Control


BorderWidth Property

See Also	Example	Applies To

Returns or sets the width of a control's border.

Syntax

object.BorderWidth [= number]

The BorderWidth property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression from 1 to 8192, inclusive.

Remarks

Use the BorderWidth and BorderStyle properties to specify the kind of border you want for a Line or 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 [image] 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 the BorderWidth property setting is greater than 1, the only effective settings of BorderStyle are 1 (Solid) and 6 (Inside Solid).


 See Also

BorderStyle Property

DrawWidth Property

Height, Width Properties


BorderWidth Property Applies To

Line Control

Shape Control


Cancel Property

See Also	Applies To

Returns or sets a value indicating whether a command button is the Cancel button on a form.  This command button can be the CommandButton control or any object within an OLE container control that behaves as a command button.

Syntax

object.Cancel [= boolean]

The Cancel property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the object is the Cancel button, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The CommandButton control is the Cancel button.

False	(Default) The CommandButton control isn't the Cancel button.

Remarks

Use the Cancel property to give the user the option of canceling uncommitted changes and returning the form to its previous state.

Only one CommandButton control on a form can be the Cancel button.  When the Cancel property is set to True for one CommandButton, it's automatically set to False for all other CommandButton controls on the form.  When a CommandButton control's Cancel property setting is True and the form is the active form, the user can choose the CommandButton by clicking it, pressing the ESC key, or pressing ENTER when the button has the focus.

For OLE container controls, the Cancel property is provided only for those objects that specifically behave as command buttons.

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.


 See Also

Default Property

KeyDown, KeyUp Events

KeyPress Event


Cancel Property Applies To

CommandButton Control

OLE Container Control


CancelError Property

Applies To

Returns or sets a value indicating whether an error is generated when the user chooses the Cancel button.

Syntax

object.CancelError [= boolean]

The CancelError property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression indicating whether an error is generated, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	An error is generated.

False	(Default) No error is generated.

Remarks

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


CancelError Property Applies To

CommonDialog Control


Col, Row Properties

See Also	Example	Applies To

Return or set the active cell in a Grid control.  Not available at design time.

Syntax

object.Col [= number]

object.Row [= number]

The Col and Row property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	The number of the column or row containing the active cell.

Remarks

Use these properties to specify a cell in a Grid control or to find out which column or row 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 doesn't change which cells are selected.  Use the SelEndCol, SelStartCol, SelEndRow, and SelStartRow properties to specify a selected region.

Note   The Col and Row properties aren't the same as the Cols and Rows properties.


See Also

Clip Property

Cols, Rows Properties

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Text Property


Col, Row Properties Apply To

DBGrid Control

Grid Control


Cols, Rows Properties

See Also	Example	Applies To

Return or set the total number of columns or rows in a Grid control.

Syntax

object.Cols [= number]

object.Rows [= number]

The Cols and Rows property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	The number of columns or rows in a Grid control.  The minimum number of columns is 1, the maximum is 400; the minimum number of rows is 1, the maximum is 2000.

Remarks

Use these properties to expand a Grid control dynamically at run time.  A Grid control must have at least one non-fixed column and one non-fixed row.

Note   The Cols and Rows properties aren't the same as the Col and Row properties.


See Also

Col, Row Properties


Cols, Rows Properties Apply To

Grid Control


ControlBox Property

See Also	Applies To

Returns or sets a value indicating whether a Control-menu box is displayed on a form at run time.  Read-only at run time.

Syntax

object.ControlBox

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

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 Dialog).

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.

Note   Settings you specify for the ControlBox, BorderStyle, MaxButton, and MinButton properties aren't reflected in the form's appearance until run time.


 See Also

BorderStyle Property

MaxButton Property

MinButton Property


ControlBox Property Applies To

Form Object


DefaultExt Property

Applies To

Returns or sets the default filename extension for the dialog box.

Syntax

object.DefaultExt [= string]

The DefaultExt property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying the file extension.

Remarks

Use this property to specify a default filename 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 filename.


DefaultExt Property Applies To

CommonDialog Control


DialogTitle Property

Applies To

Returns or sets the string displayed in the title bar of the dialog box.

Syntax

object.DialogTitle [= title]

The DialogTitle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

title	A string expression specifying the name of the dialog box.

Remarks

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

Note   The CommonDialog control ignores the setting of the DialogTitle property when displaying the Color or Font dialog boxes.

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


DialogTitle Property Applies To

CommonDialog Control


DrawWidth Property

See Also	Example	Applies To

Returns or sets the line width for output from graphics methods.

Syntax

object.DrawWidth [= size]

The DrawWidth property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

size	A numeric expression from 1 through 32,767.  This value represents the width of the line in pixels.  The default is 1; that is, 1 pixel wide.

Remarks

Increase the value of this property to increase the width of the line.  If the DrawWidth property setting 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.


 See Also

Circle Method

DrawMode Property

DrawStyle Property

FillColor Property

FillStyle Property

ForeColor Property


DrawWidth Property Applies To

Form Object

PictureBox Control

Printer Object


FileTitle Property

Applies To

Returns the name (without the path) of the file to open or save.

Syntax

object.FileTitle

The object placeholder is an object expression that evaluates to an object in the Applies To list.

Remarks

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

Note   If the cdlOFNNoValidate flag is set, the FileTitle property won't return a value.


FileTitle Property Applies To

CommonDialog Control


Filter Property (CommonDialog)

See Also	Applies To

Returns or sets the filters that are displayed in the Type list box of a dialog box.

Syntax

object.Filter [= description1 |filter1 |description2 |filter2...]

The Filter property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

description	A string expression describing the type of file.

filter	A string expression specifying the filename extension.

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 values.  Don't include spaces before or after the pipe symbol, because these spaces will be displayed with the description and filter values.

The following code shows an example of a filter that enables the user to select text files or graphic 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.


Filter Property (CommonDialog) Applies To

CommonDialog Control


See Also

FilterIndex Property


FilterIndex Property

See Also	Applies To

Returns or sets a default filter for an Open or Save As dialog box.

Syntax

object.FilterIndex [= number]

The FilterIndex property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying a default filter.

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.


FilterIndex Property Applies To

CommonDialog Control


See Also

Filter Property


Flags Property (Color Dialog)

See Also	Applies To

Returns or sets the options for a Color dialog box.

Syntax

object.Flags [= value]

The Flags property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value specifying the options for a Color dialog box, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

cdCClFullOpen	&H2&	Causes the entire dialog box, including the portion that enables the user to create custom colors, to be displayed 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.

cdlCCPreventFullOpen	&H4&	Disables the Define Custom Colors command button and prevents the user from defining custom colors.

cdlCCRGBInit	&H1&	Sets the initial color value for the dialog box.

cdlCCShowHelp	&H8&	Causes the dialog box to display a Help button.

Remarks

These constants are listed in the Microsoft CommonDialog Control (MSComDlg) object library in the Object Browser.

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&


See Also

Const Statement

Or Operator


Flags Property (Color Dialog) Applies To

CommonDialog Control


Flags Property (File Dialog)

See Also	 	Applies To

Returns or sets the options for the Open and Save As dialog boxes.

Syntax

object.Flags [= value]

The Flags property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value specifying the options for the Open and Save As dialog boxes, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description
cdlOFNAllowMultiselect	&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 ARROW 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.
cdlOFNCreatePrompt	&H2000&	Specifies that the dialog box prompts the user to create a file that doesn't currently exist.  This flag automatically sets the cdlOFNPathMustExist and cdlOFNFileMustExist flags.
cdlOFNExtensionDifferent	&H400&	Indicates that the extension of the returned filename is different from the extension specified by the DefaultExt property.  This flag isn't 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 closing the dialog box.
cdlOFNFileMustExist	&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 filename, a warning is displayed.  This flag automatically sets the cdlOFNPathMustExist flag.
cdlOFNHideReadOnly	&H4&	Hides the Read Only check box.
cdlOFNNoChangeDir	&H8&	Forces the dialog box to set the current directory to what it was when the dialog box was opened.
cdlOFNNoReadOnlyReturn	&H8000&	Specifies that the returned file won't have the Read Only attribute set and won't be in a write-protected directory.
cdlOFNNoValidate	&H100&	Specifies that the common dialog box allows invalid characters in the returned filename.
cdlOFNOverwritePrompt	&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.
cdlOFNPathMustExist	&H800&	Specifies that the user can enter only valid paths.  If this flag is set and the user enters an invalid path, a warning message is displayed.
cdlOFNReadOnly	&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.
cdlOFNShareAware	&H4000&	Specifies that sharing violation errors will be ignored.
cdlOFNHelpButton	&H10&	Causes the dialog box to display the Help button.
cdlOFNExplorer	&H8000&	Specifies using the Windows 95 explorer-like Open A File dialog box templete.  (Windows 95 only.)
cdlOFNNoDereferenceLinks	&H100000&	Do not dereference shortcuts (shell links).  By default, choosing a shortcut causes it to be dereferenced by the shell.  (Windows 95 only.)
cdOFNLongNames	&H200000&	Allows the user to use long filenames. Windows 95 only.)
Remarks

These constants are listed in the Microsoft CommonDialog Control (MSComDlg) object library in the Object Browser.

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 ReadOnly  = &H00000001&
Const 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&


See Also

Const Statement

DefaultExt Property

FileName Property


Flags Property (File Dialog) Applies To

CommonDialog Control


Flags Property (Font Dialog)

Applies To

Returns or sets the options for the Font dialog box.

Syntax

object.Flags [= value]

The Flags property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value specifying the options for a Font dialog box, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description
cdlCFANSIOnly	&H400&	Specifies that the dialog box allows only a selection of the fonts that use the Windows character set.  If this flag is set, the user won't be able to select a font that contains only symbols.
cdlCFBoth	&H3&	Causes the dialog box to list the available printer and screen fonts.  The hDC property identifies the device context associated with the printer.
cdlCFEffects	&H100&	Specifies that the dialog box enables strikethrough, underline, and color effects.
cdlCFFixedPitchOnly	&H4000&	Specifies that the dialog box selects only fixed-pitch fonts.
cdlCFForceFontExist	&H10000&	Specifies that an error message box is displayed if the user attempts to select a font or style that doesn't exist.
cdlCFLimitSize	&H2000&	Specifies that the dialog box selects only font sizes within the range specified by the Min and Max properties.
cdlCFNoSimulations	&H1000&	Specifies that the dialog box doesn't allow graphic device interface (GDI) font simulations.
cdlCFNoVectorFonts	&H800&	Specifies that the dialog box doesn't allow vector-font selections.
cdlCFPrinterFonts	&H2&	Causes the dialog box to list only the fonts supported by the printer, specified by the hDC property.
cdlCFScalableOnly	&H20000&	Specifies that the dialog box allows only the selection of fonts that can be scaled.
cdlCFScreenFonts	&H1&	Causes the dialog box to list only the screen fonts supported by the system.
cdlCFHelpButton	&H4&	Causes the dialog box to display a Help button.
cdlCFTTOnly	&H40000&	Specifies that the dialog box allows only the selection of TrueType fonts.
cdlCFWYSIWYG	&H8000&	Specifies that the dialog box allows only the selection of fonts that are available on both the printer and on screen.  If this flag is set, the cdlCFBoth and cdlCFScalableOnly flags should also be set.
Remarks

These constants are listed in the Microsoft CommonDialog Control (MSComDlg) object library in the Object Browser.

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 ReadOnly  = &H00000001&

Const 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&

Note   You must set the Flags property to cdlCFScreenFonts, cdlCFPrinterFonts, or cdlCFBoth before displaying the Fonts dialog box.  Otherwise, the error No Fonts Exist occurs.


See Also

hDC Property

Max, Min Properties (CommonDialog)

Const Statement

Or Operator


Flags Property (Font Dialog) Applies To

CommonDialog Control


Flags Property (Print Dialog)

See Also	Applies To

Returns or sets the options for the Print dialog box.

Syntax

object.Flags [= value]

The Flags property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value specifying the options for the Print dialog box, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description
cdlPDAllPages	&H0&	Returns or sets the state of the All Pages option button.
cdlPDCollate	&H10&	Returns or sets the state of the Collate check box.
cdlPDDisablePrintToFile	&H80000&	Disables the Print To File check box.
cdlPDHidePrintToFile	&H100000&	Hides the Print To File check box.
cdlPDNoPageNums	&H8&	Disables the Pages option button and the associated edit control.
cdlPDNoSelection	&H4&	Disables the Selection option button.
cdlPDNoWarning	&H80&	Prevents a warning message from being displayed when there is no default printer.
cdlPDPageNums	&H2&	Returns or sets the state of the Pages option button.
cdlPDPrintSetup	&H40&	Causes the system to display the Print Setup dialog box rather than the Print dialog box.
cdlPDPrintToFile	&H20&	Returns or sets the state of the Print To File check box.
cdlPDReturnDC	&H100&	Returns a device context for the printer selection made in the dialog box.  The device context is returned in the dialog box's hDC property.
cdlPDReturnIC	&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 box's hDC property.
cdlPDReturnDefault	&H400&	Returns default printer name.
cdlPDSelection	&H1&	Returns or sets the state of the Selection option button.  If neither cdlPDPageNums nor cdlPDSelection is specified, the All option button is in the selected state.
cdlPDHelpButton	&H800&	Causes the dialog box to display the Help button.
cdlPDUseDevModeCopies	&H40000&	If a printer driver doesn't 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 stores the requested number of copies in the Copies property.
Remarks

These constants are listed in the Microsoft CommonDialog Control (MSComDlg) object library in the Object Browser.

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 ReadOnly  = &H00000001&

Const 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&


Flags Property (Print Dialog) Applies To

CommonDialog Control


See Also

Const Statement

Copies Property

hDC Property

Or Operator


FontBold, FontItalic, FontStrikethru, FontUnderline Properties

See Also	Example	Applies To

Return or set font styles in the following formats: Bold, Italic, Strikethru, and Underline.

Note   The FontBold, FontItalic, FontStrikethru, and FontUnderline properties are included for use with the CommonDialog control and for compatibility with earlier versions of Visual Basic.  For additional functionality, use the new Font object properties (not available for the CommonDialog control).

Syntax

object.FontBold [= boolean]

object.FontItalic [= boolean]

object.FontStrikethru [= boolean]

object.FontUnderline [= boolean]

The FontBold, FontItalic, FontStrikethru, and FontUnderline property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the font style as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default for FontBold, except with the CommonDialog control) Turns on the formatting in that style.

False	(Default for FontItalic, FontStrikethru, and FontUnderline, and FontBold with the CommonDialog control) Turns off the formatting in that style.

Remarks

Use these font properties to format text, either at design time using the Properties window or at run time using code.  For PictureBox controls and Form and Printer objects, setting these properties doesn't affect graphics or text already drawn on the control or object.  For all other controls, font changes take effect on screen immediately.

To use these properties with the CommonDialog control, the Effects flag must be set.

Note   Fonts available in Visual Basic vary depending on 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, 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 Microsoft Windows operating environment uses a different font for TrueType fonts that are smaller than 8 points.


 See Also

Font Object

FontName Property

FontSize Property

TextHeight Method

TextWidth Method


FontBold, FontItalic, FontStrikethru, FontUnderline Properties Applies To
FontBold, FontItalic, FontStrikethru, FontUnderline Properties Apply To

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Label Control

ListBox Control

OptionButton Control

PictureBox Control

Printer Object

TextBox Control


FontName Property

See Also	Example	Applies To

Returns or sets the font used to display text in a control or in a run-time drawing or printing operation.

Note   The FontName property is included for use with the CommonDialog control and for compatibility with earlier versions of Visual Basic.  For additional functionality, use the new Font object properties (not available for the CommonDialog control).

Syntax

object.FontName [= font]

The FontName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

font	A string expression specifying the font name to use.

Remarks

The default for this property is determined by the system.  Fonts available with Visual Basic vary depending on 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, and FontUnderline properties.

Note   At run time, you can get information on fonts available to the system through the FontCount and Fonts properties.


See Also

FontBold, FontItalic, FontStrikethru, FontUnderline Properties

FontCount Property

Fonts Property

FontSize Property

Print Method

TextHeight Method

TextWidth Method


FontName Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Label Control

ListBox Control

OptionButton Control

PictureBox Control

Printer Object

TextBox Control


FontSize Property

See Also	Example	Applies To

Returns or sets the size of the font to be used for text displayed in a control or in a run-time drawing or printing operation.

Note   The FontSize property is included for use with the CommonDialog control and for compatibility with earlier versions of Visual Basic.  For additional functionality, use the new Font object properties (not available for the CommonDialog control).

Syntax

object.FontSize [= points]

The FontSize property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

points	A numeric expression specifying the font size to use, in 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 2160 points.

Note   Fonts available with Visual Basic vary depending on 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, 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 Microsoft Windows operating environment uses a different font for TrueType fonts that are smaller than 8 points.


See Also

FontBold, FontItalic, FontStrikethru, FontUnderline Properties

FontCount Property

FontName Property

Fonts Property


FontSize Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Label Control

ListBox Control

OptionButton Control

PictureBox Control

Printer Object

TextBox Control


FromPage, ToPage Properties

Applies To

Return or set the values for the From and To text boxes.

Syntax

object.FromPage [= number]

object.ToPage [= number]

The FromPage and ToPage property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that specifies the first and last pages to be printed.

Remarks

These properties are valid only when the cdlPDPageNums flag has been set.


FromPage, ToPage Properties Apply To

CommonDialog Control (Print Dialog)


Height, Width Properties

See Also	Example	Applies To

Return or set the dimensions of an object or the width of the Columns object of a DBGrid control.  For the Printer and Screen objects, not available at design time.

Syntax

object.Height [= number]

object.Width [= number]

The Height and Width property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying the dimensions of an object, as described in Settings.

Settings

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.  If set at run time, values in these properties are used instead of the setting of the PaperSize property.

Screen object [image] the height and width of the screen; not available at design time and read-only at run time.

Picture object [image] the height and width of the picture in HiMetric units.

Remarks

For Form, Printer, and Screen objects, 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 your code.  Maximum limits of these properties for all objects are system-dependent.

If you set the Height and Width properties for a printer driver that doesn't allow these properties to be set, no error occurs and the size of the paper remains as it was.  If you set Height and Width for a printer driver that allows only certain values to be specified, no error occurs and the property is set to whatever the driver allows.  For example, you could set Height to 150 and the driver would set it to 144.

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 the DriveListBox control or for the ComboBox control, whose Style property setting is 0 (Dropdown Combo) or 2 (Dropdown List).

For the Columns object of the DBGrid control, Width is specified in the unit of measure of the object that contains the DBGrid.  The default value for Width is the value of the DefColWidth property of DBGrid.

For the Picture object, use the ScaleX and ScaleY methods to convert HiMetric units into the scale you need.


See Also

DBGrid Control

DefColWidth Property

Left, Top Properties

Move Method

PaperSize Property

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleX, ScaleY Methods

Width # Statement


Height, Width Properties Apply To

CheckBox Control

Columns Object

ComboBox Control

CommandButton Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

Picture Object

PictureBox Control

Printer Object

Screen Object

Shape Control

TextBox Control


HelpCommand Property

See Also	Applies To

Returns or sets the type of online Help requested.

Syntax

object.HelpCommand [= value]

The HelpCommand property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value specifying the type of Help, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description
cdlHelpCommand	&H102	Executes a Help macro.
cdlHelpContents	&H3	Displays the Help contents topic as defined by the Contents option in the [OPTION] section of the .HPJ file.
cdlHelpContext	&H1	Displays Help for a particular context.  When using this setting, you must also specify a context using the HelpContext property.
cdlHelpContextPopup	&H8	Displays in a pop-up window a particular Help topic identified by a context number defined in the [MAP] section of the .HPJ file.
cdlHelpForceFile	&H9	Ensures that WinHelp displays the correct Help file.  If the correct Help file is currently displayed, no action occurs.  If the incorrect Help file is displayed, WinHelp opens the correct file.
cdlHelpHelpOnHelp	&H4	Displays Help for using the Help application itself.
cdlHelpIndex	&H3	Displays the index of the specified Help file.  An application should use this value only for a Help file with a single index.
cdlHelpKey	&H101	Displays Help for a particular keyword.  When using this setting, you must also specify a keyword using the HelpKey property.
cdlHelpPartialKey	&H105	Displays the topic found in the keyword list that matches the keyword passed in the dwData parameter if there is one exact match.  If more than one match exists, the Search dialog box with the topics found listed in the Go To list box is displayed.  If no match exists, the Search dialog box is displayed.  To bring up the Search dialog box without passing a keyword, use a long pointer to an empty string.
cdlHelpQuit	&H2	Notifies the Help application that the specified Help file is no longer in use.
cdlHelpSetContents	&H5	Determines which contents topic is displayed when a user presses the F1 key.
cdlHelpSetIndex	&H5	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.
Remarks

The values for the HelpCommand property constants are listed in the Microsoft CommonDialog Control (MSComDlg) object library in the Object Browser.


HelpCommand Property Applies To

CommonDialog Control


See Also

HelpContext Property

HelpFile Property

HelpKey Property


HelpContext Property (CommonDialog)

See Also 	Applies To

Returns or sets the context ID of the requested Help topic.

Syntax

object.HelpContext [= value]

The HelpContext property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression specifying the context ID of the requested Help topic.

Remarks

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


HelpContext Property Applies To

CommonDialog Control


See Also

HelpCommand Property


HelpKey Property

See Also	Applies To

Returns or sets the keyword that identifies the requested Help topic.

Syntax

object.HelpKey [= string]

The HelpKey property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying the keyword that identifies the Help topic.

Remarks

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


HelpKey Property Applies To

CommonDialog Control


See Also

HelpCommand Property


Icon Property

See Also	Example	Applies To

Returns the icon displayed when a form is minimized at run time.

Syntax

object.Icon

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use this property to specify an icon for any form that the user can minimize at run time.

For example, you can assign an 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 filename extension and format.  If you don't specify an icon, the Visual Basic default icon for forms is used.

You can use the Visual Basic 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 without an argument assigns an empty (null) icon to the form, which enables you to draw on the icon at run time.


 See Also

LoadPicture Function


Icon Property Applies To

Form Object

MDIForm Object


InitDir Property

Applies To

Returns or sets the initial file directory.

Syntax

object.InitDir [= string]

The InitDir property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying the initial file directory.

Remarks

If this property isn't specified, the current directory is used.


InitDir Property Applies To

CommonDialog Control (File Dialog)


Interval Property

See Also	Example	Applies To

Returns or sets the number of milliseconds between calls to a Timer control's Timer event.

Syntax

object.Interval [= milliseconds]

The Interval property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

milliseconds	A numeric expression specifying the number of milliseconds, as described in Settings.

Settings

The settings for milliseconds are:

Setting	Description

0	(Default) Disables a Timer control.

1 to 65,535 	Sets an interval (in milliseconds) that takes effect when a Timer control's Enabled property is set to True.  For example, a value of 10,000 milliseconds equals 10 seconds.  The maximum, 65,535 milliseconds, is equivalent to just over 1 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 control responds to the passage of time.  Set Enabled to False to turn a Timer control off, and to True to turn it on.  When a Timer control is enabled, its countdown always starts from the value of its Interval property setting.

Create 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.


See Also

Enabled Property


Interval Property Applies To

Timer Control


Left, Top Properties

See Also	Example	Applies To

Left [image] returns or sets the distance between the internal left edge of an object and the left edge of its container.

Top [image] returns or sets the distance between the internal top edge of an object and the top edge of its container.

Syntax

object.Left [= value]

object.Top [= value]

The Left and Top property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying distance.

Remarks

For a form, the Left and Top properties are always expressed in twips; for a control, they are measured in units depending on 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 control, these properties aren't available at run time.

For both properties, you can specify a single-precision number.

Use the Left, Top, 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 PictureBox controls and Form and Printer objects.


 See Also

Left Function

Move Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property


Left, Top Properties Apply To

CheckBox Control

Column Object

ComboBox Control

CommandButton Control

CommonDialog Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

Timer Control


List Property

See Also	Example	Applies To

Returns or sets the items contained in a control's list portion.  The list is a string array in which each element is a list item.  Available at design time for ListBox and ComboBox controls through the property browser; read-only at run time for DirListBox, DriveListBox, and FileListBox controls; read/write at run time for ComboBox and ListBox controls.

Syntax

object.List(index) [= string]

The List property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	The number of a specific item in the list.

string	A string expression specifying the list item.

Remarks

Use this property to access list items.

For all controls except the DirListBox, the index of the first item is 0 and the index of the last item is ListCount [image] 1.

For a DirListBox control, the index number sequence is based on the current directories and subdirectories when the control is created at run time.  The directory that is currently expanded is represented using the index [image] 1.  Directories above the currently expanded directory are represented by negative indexes with higher absolute values.  For example, [image] 2 is the parent directory of the directory that is currently expanded and [image] 3 is the directory above that.  Directories below the directory that is currently expanded range from 0 to ListCount [image] 1.

Initially, ComboBox and ListBox controls 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:

DirListBox [image] contains a list of all directories, using the range -n to ListCount [image] 1.

DriveListBox [image] contains the list of drive connections in effect.

FileListBox [image] contains the list of files in the directory that is currently expanded that match the Pattern property.  The path isn't included.

The List property works in conjunction with the ListCount and ListIndex properties.

For all applicable controls except a DirListBox, enumerating a list from 0 to ListCount -1 returns all items in the list.  For a DirListBox control, enumerating the list from [image] n to ListCount [image] 1 returns a list containing all directories and subdirectories visible from the directory that is currently expanded.  In this case n is the number of directory levels above the directory that is currently expanded.

Note   To specify items you want to display in a ComboBox or ListBox control, use the AddItem method.  To remove items, use the RemoveItem method.  To keep items in alphabetic 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 doesn't 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, a zero-length string ("") is returned.  For example, List(-1) returns a zero-length string for a ComboBox or ListBox control.


See Also

AddItem Method

ListCount Property

ListIndex Property

Pattern Property

RemoveItem Method

Sorted Property


List Property Applies To

ComboBox Control

DirListBox Control

DriveListBox Control

FileListBox Control

ListBox Control


ListCount Property

See Also	Example	Applies To

Returns the number of items in the list portion of a control.

Syntax

object.ListCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

ListCount provides specific information for each control:

ComboBox and ListBox controls [image] the number of items in the list.

DirListBox control [image] the number of subdirectories in the current directory.

DriveListBox control [image] the number of drive connections.

FileListBox control [image] the number of files in the current directory that match the Pattern property setting.

If no item is selected, the ListIndex property value is [image] 1.  The first item in the list is ListIndex = 0, and ListCount is always one more than the largest ListIndex value.


 See Also

AddItem Method

List Property

ListIndex Property

Pattern Property

RemoveItem Method


ListCount Property Applies To

ComboBox Control

DirListBox Control

DriveListBox Control

FileListBox Control

ListBox Control


ListIndex Property

See Also	Example	Applies To

Returns or sets the index of the currently selected item in the control.  Not available at design time.

Syntax

object.ListIndex [= index]

The ListIndex property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	A numeric expression specifying the index of the current item, as described in Settings.

Settings

The settings for index are:

Setting	Description

1	(Default for ComboBox, DirListBox, and DriveListBox controls) Indicates no item is currently selected.  For a ComboBox control, indicates the user has entered new text into the text box portion.  For a DirListBox control, indicates the index of the current path.  For a DriveListBox control, indicates the index of the current drive when the control is created at run time.

n	(Default for FileListBox and ListBox controls) 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.

For a control in which users can make multiple selections, this property's behavior depends on the number of items selected.  If only one item is selected, ListIndex returns the index of that item.  In a multiple selection, ListIndex returns the index of the item contained within the focus rectangle, whether or not that item is actually selected.


See Also

AddItem Method

Drive Property

List Property

ListCount Property

Path Property

RemoveItem Method


ListIndex Property Applies To

ComboBox Control

DirListBox Control

DriveListBox Control

FileListBox Control

ListBox Control


Max, Min Properties (CommonDialog)

Applies To

You can set the Max and Min properties for the following:

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

Print dialog box [image] return or set the minimum and maximum allowed values for the print range.

Syntax

object.Min [= points]

object.Max [= points]

object.Min [= number ]

object.Max [= number ]

The Max and Min property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

points	A numeric expression specifying the smallest and largest font sizes.

number	A numeric expression specifying the minimum and maximum page numbers.

Remarks

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

With the Print dialog box, 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.


Max, Min Properties Apply To

CommonDialog Control


MaxButton Property

See Also	Applies To

Returns a value indicating whether a form has a Maximize button.

Syntax

object.MaxButton

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The MaxButton property settings are:

Setting	Description

True	(Default) The form has a Maximize button.

False	The form doesn't 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 the MaxButton, MinButton, BorderStyle, and ControlBox properties aren't reflected in the form's appearance until run time.

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.


See Also

ControlBox Property

MinButton Property


MaxButton Property Applies To

Form Object


MinButton Property

See Also	Applies To

Returns a value indicating whether a form has a Minimize button.

Syntax

object.MinButton

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The MinButton return values are:

Setting	Description

True	(Default) The form has a Minimize button.

False	The form doesn't have a Minimize button.

Remarks

A Minimize button enables users to minimize 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 the MaxButton, MinButton, BorderStyle, and ControlBox properties aren't reflected in the form's appearance until run time.

Note   Minimizing 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.


See Also

ControlBox Property

MaxButton Property


MinButton Property Applies To

Form Object


Picture Property

See Also	Example	Applies To

Returns or sets a graphic to be displayed in a control.  For the OLE container control, not available at design time and read-only at run time.

Syntax

object.Picture [= picture]

The Picture property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

picture	A string expression specifying a file containing a graphic, as described in Settings.

Settings

The settings for picture 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 nontext Clipboard constants vbCFBitmap, vbCFMetafile, and vbCFDIB, which are listed in the Visual Basic (VB) object library in the Object Browser.

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 isn't 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.


See Also

AutoRedraw Property

Icon Property

LoadPicture Function

SavePicture Statement


Picture Property Applies To

Form Object

Image Control

MDIForm Object

OLE Container Control

PictureBox Control


PrinterDefault Property

Applies To

Returns or sets an option that determines if the user's selections in the Print dialog box are used to change the system's default printer settings.

Syntax

object.PrinterDefault [= value]

The PrinterDefault property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression specifying whether the user's selections are used to change the system's default printer settings, as described in Settings.

Settings

The settings for value are:

Setting	Description

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.  (On the Windows NT operating system, this information is stored in the Registry.)

False	User's selections can't be used to change the system's default printer settings.

Remarks

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

Note   If you've previously printed to the Printer object, make sure you've 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's possible for the user to select a new printer while the Printer object contains a handle to the old printer.


PrinterDefault Property Applies To

CommonDialog Control


Sorted Property

See Also	Applies To

Returns a value indicating whether the elements of a control are automatically sorted alphabetically.

Syntax

object.Sorted

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Sorted property return values are:

Setting	Description

True	List items are sorted alphabetically (case-insensitive).

False	(Default) List items aren't sorted alphabetically.

Remarks

When this property is True, Visual Basic handles almost all necessary string processing to maintain alphabetic 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.


See Also

AddItem Method

List Property

ListCount Property

ListIndex Property

RemoveItem Method


Sorted Property Applies To

ComboBox Control

ListBox Control


TabIndex Property

See Also	Example	Applies To

Returns or sets the tab order of an object within its parent form.

Syntax

object.TabIndex [= index]

The TabIndex property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer from 0 to (n [image] 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 can't receive the focus (Frame and Label controls) remain in the tab order but are skipped during tabbing.

The TabIndex property isn't affected by the ZOrder method.

Note   A control's tab order doesn't affect its associated access key.  If you press the access key for a Frame or Label control, 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.


See Also

TabStop Property

ZOrder Method


TabIndex Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


Tag Property

See Also	Example	Applies To

Returns or sets an expression that stores any extra data needed for your program.  Unlike other properties, the value of the Tag property isn't used by Visual Basic; you can use this property to identify objects.

Syntax

object.Tag [= expression]

The Tag property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

expression	A string expression identifying the object.  The default is a zero-length string ("").

Remarks

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 MDIForm object that is passed as a variable to a procedure.

Tip   When you create a new instance of a form, assign a unique value to the Tag property.


See Also

Name Property


Tag Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

DBCombo Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

Line Control

ListBox Control

MDIForm Object

Menu Object

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

Timer Control


Text Property

See Also	Example	Applies To

ComboBox control (Style property set to 0 [Dropdown Combo] or to 1 [Simple Combo]) and TextBox control [image] returns or sets the text contained in the edit area.

ComboBox control (Style property set to 2 [Dropdown List]) and ListBox control [image] returns 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.

Grid control [image] returns or sets the text contained in a cell or range of cells.  Not available at design time.

Syntax

object.Text [= string]

The Text property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression specifying text.

Remarks

At design time only, the defaults for the Text property are:

ComboBox and TextBox controls [image] the control's Name property.

ListBox control [image] a zero-length string ("").

For a ComboBox with the Style property set to 0 (Dropdown Combo) or to 1 (Simple Combo) or for a TextBox, this property is useful for reading the actual string contained in the edit area of the control.  For a ComboBox or ListBox control with the Style property set to 2 (Dropdown List), you can use the Text property to determine the currently selected item.

The Text setting for a TextBox control is limited to 2048 characters unless the MultiLine property is True, in which case the limit is about 32K.

For a Grid control, you can add text to a single cell by setting the Text property.  This property applies to the cell defined by the current values of the Grid control's Row and Col properties.

You can use the Text and FillStyle properties to add the same text to a highlighted range of cells.  When FillStyle = 0, the text assigned to the Text property is added only to the cell defined by the current Row and Col property values.  When FillStyle = 1, the text is added to all cells whose CellSelected property setting is True.

You can also use the Clip property to fill a range of cells.  For example, you might want to paste a large block of information from the Clipboard into a Grid control.


See Also

SelLength, SelStart, SelText Properties

Value Property


Text Property Applies To

Column Object

ComboBox Control

DBCombo Control

DBGrid Control

DBList Control

Grid Control

ListBox Control

TextBox Control


Value Property

See Also	Example	Applies To

CheckBox and OptionButton controls [image] returns or sets the state of the control.

CommandButton control [image] returns or sets a value indicating whether the button is chosen; not available at design time.

Field object [image] returns or sets the content of a field; not available at design time.

HScrollBar and VScrollBar controls (horizontal and vertical scroll bars) [image] returns or sets the current position of the scroll bar, whose return value is always between the values for the Max and Min properties, inclusive.

Syntax

object.Value [= value]

The Value property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	Value specifying the state, content, or position of a control, as described in Settings.

Settings

The settings for value are:

CheckBox control [image] 0 is Unchecked (default), 1 is Checked, and 2 is Grayed (dimmed).

CommandButton control [image] True indicates the button is chosen; False (default) indicates the button isn't 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.

HScrollBar and VScrollBar controls [image] set values between [image] 32,768 and 32,767 to position the scroll box.

OptionButton control [image] True indicates the button is selected; False (default) indicates the button isn't selected.

Remarks

A default property of an object is assumed, and doesn't 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.


See Also

Max, Min Properties (Scroll Bar)


Value Property Applies To

CheckBox Control

Column Object

CommandButton Control

HScrollBar, VScrollBar Controls

OptionButton Control


Visible Property

See Also	Example	Applies To

Returns or sets a value indicating whether an object is visible or hidden.

Syntax

object.Visible [= boolean]

The Visible property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the object is visible or hidden.

Settings

The settings for boolean are:

Setting	Description

True	(Default) Object is visible.

False	Object is hidden.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

To hide an object at startup, set the Visible property to False at design time.  Setting this property in code enables 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.


See Also

Hide Method

Load Statement

Make OLE DLL File Command

Show Method


Visible Property Applies To

CheckBox Control

Column Object

ComboBox Control

CommandButton Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

Line Control

ListBox Control

MDIForm Object

Menu Object

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control


BackColor, ForeColor Properties Example

This example resets foreground and background colors randomly twice each second for a form and PictureBox control.  To try this example, paste the code into the Declarations section of a form that contains a PictureBox control and a Timer control, and then press F5.

Private Sub Form_Load ()

Timer1.Interval = 500

End Sub

Private Sub Timer1_Timer ()

BackColor = QBColor(Rnd * 15)

ForeColor = QBColor(Rnd * 10)

Picture1.BackColor = QBColor(Rnd * 15)

Picture1.ForeColor = QBColor(Rnd * 10)

End Sub


BorderWidth Property Example

This example uses two ComboBox controls 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 ComboBox control.  For the ComboBox, set Style = 2 and Index = 0 (to create a control array), and then press F5 and click the form.

Private 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

Private 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


Col, Row Properties Example

This 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 Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control) to add GRID16.OCX or GRID32.OCX to the project, and then draw a grid on a new form.  To run the program, press F5, and then click the grid.

Private Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

End Sub

Private Sub Grid1_Click ()

' Put text in current cell.

Grid1.Text = "Here"

' Put text in third row, third column.

Grid1.Col = 2

Grid1.Row = 2

Grid1.Text = "There"

End Sub

The next example displays the location of the active cell and the range of the selection as a user selects a cell or range of cells.  Notice that when selecting a range, the active cell doesn't 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 doesn't change.

To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a grid and two labels.  Copy the code into the Declarations section, and then press F5 to run the program.

Private Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Private Sub Grid1_RowColChange ()

Msg = "Active Cell: " & Chr(64 + Grid1.Col)

Mst = Msg & Grid1.Row

Label1.Caption = Msg

End Sub

Private 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

Private Sub Form_Click ()

' This procedure moves the active cell around

' the perimeter of the 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


DrawWidth Property Example

This example draws a gradually thickening line across a form.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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


FontBold, FontItalic, FontStrikethru, FontUnderline Properties Example

This 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, and then press F5 and click the form.

Private Sub Form_Click ()

FontStrikethru = Not FontStrikethru	' Toggle strikethrough.

FontItalic = Not FontItalic	' Toggle font style.

Print "Now is the time!"	' Print some text.

End Sub


FontName Property Example

This 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.

Private 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 Example

This 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.

Private 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 Example

This example sets the size of a form to 75 percent 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.

Private Sub Form_Click ()

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


Icon Property Example

This 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, and then press F5 and minimize the form.

Private 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 Example

This example enables 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 control, an HScrollBar control (horizontal scroll bar), and a PictureBox control, and then press F5 and click the scroll bar.

Private Sub Form_Load ()

Timer1.Interval = 900	' Set interval.

HScroll1.Min = 100	' Set minimum.

HScroll1.Max = 900	' Set maximum.

End Sub

Private Sub HScroll1_Change ()

' Set interval according to scroll bar value.

Timer1.Interval = 1000 - HScroll1.Value

End Sub

Private 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


Left, Top Properties Example

This example sets the size of a form to 75 percent of screen size and centers the form when it's loaded.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private Sub Form_Click ()

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


List Property Example

This example loads a ComboBox control 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 ComboBox control, and then press F5.

Private 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 Example

This example loads a list of your printer fonts into a ComboBox control, displays the first item in the list, and prints the total number of fonts.  Each click of the command 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 ComboBox control (Style = 2) and a CommandButton control, and then press F5 and click the CommandButton.

Private 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 information on form.

Print "Number of printer fonts: "; Combo1.ListCount

End Sub

Private 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 Example

This example displays the names of three players in a ListBox control and the corresponding salary of the selected player in a Label control.  To try this example, paste the code into the Declarations section of a form that contains a ComboBox control and a Label control, and then press F5 and choose a name from the ComboBox.

Dim Player(0 To 2)	' Dimension two arrays.

Dim Salary(0 To 2)

Private 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

Private Sub Combo1_Click ()

' Display corresponding salary for name.

Label1.Caption = Salary(Combo1.ListIndex)

End Sub


Picture Property Example

This example loads icons from the Visual Basic icon library into two of three PictureBox controls.  When you click the form, the third PictureBox is used to switch the icons.  You can use any two icons.  Paste the code into the Declarations section of a form that has three small PictureBox controls (for Picture3, set Visible = False).  Press F5 to run the program, and then click the form.

Private Sub Form_Load ()

' Load the icons.

Picture1.Picture = LoadPicture("ICONS\COMPUTER\TRASH02A.ICO")

Picture2.Picture = LoadPicture("ICONS\COMPUTER\TRASH02B.ICO")

End Sub

Private Sub Form_Click ()

' Switch the icons.

Picture3.Picture = Picture1.Picture

Picture1.Picture = Picture2.Picture

Picture2.Picture = Picture3.Picture

' Clear the third picture (not necessary if not visible).

Picture3.Picture = LoadPicture()

End Sub

This example pastes a bitmap from the Clipboard into a PictureBox control.  To find the value of Clipboard format constants (starting with vbCF), see the Visual Basic (VB) object library in the Object Browser.  To try this example, paste the code into the Declarations section of a form that has a PictureBox control.  Press F5, and then in another application, copy an icon onto the Clipboard, switch to Visual Basic, and click the form.

Private Sub Form_Click ()

Const vbCFBitmap = 2

Picture1.Picture = Clipboard.GetData(vbCFBitmap)

End Sub


TabIndex Property Example

This example reverses the tab order of a group of buttons by changing the TabIndex property of a command button array.  To try this example, paste the code into the Declarations section of a form that contains four CommandButton controls.  Set the Name property to CommandX for each button to create the control array, and then press F5 and click the form to reverse the tab order of the buttons.

Private 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


Tag Property Example

This 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 PictureBox controls.  Set the DragMode property to 1 for Picture1 and Picture2, and then press F5.  Use the mouse to drag Picure1 or Picture2 over Picture3 controls.

Private Sub Form_Load ()

Picture1.Tag = "Pic1"

Picture2.Tag = "Pic2"

End Sub

Private 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 isn't 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 Picture2.

Source.DragIcon = LoadPicture ("ICONS\ARROWS\POINT04.ICO")

End Select

ElseIf State = LEAVE Then

' When source isn't over Picture3, unload icon.

Source.DragIcon = LoadPicture ()

End If

End Sub


Text Property Example

This example illustrates the Text property.  To try this example, paste the code into the Declarations section of a form that contains three TextBox controls and a CommandButton control, and then press F5 and enter text in Text1.

Private Sub Text1_Change ()

Text2.Text = LCase(Text1.Text)	' Display text as lowercase.

Text3.Text = UCase(Text1.Text)	' Display text as uppercase.

End Sub

Private Sub Command1_Click ()	' Delete text.

Text1.Text = ""

End Sub


Value Property Example

This example displays an HScrollBar (horizontal scroll bar) control's numeric value in a TextBox control.  To try this example, paste the code into the Declarations section of a form that has a TextBox control and an HScrollBar control.  Press F5 to run the program, and then click the scroll bar.

Private Sub Form_Load ()

HScroll1.Min = 0	' Initialize scroll bar.

HScroll1.Max = 1000

HScroll1.LargeChange = 100

HScroll1.SmallChange = 1

End Sub

Private Sub HScroll1_Change ()

Text1.Text = Format (HScroll1.Value)

End Sub


Visible Property Example

This example creates animation using two PictureBox controls.  To try this example, paste the code into the Declarations section of a form that contains two icon-sized PictureBox controls.  Set the Name property to FileCab for both PictureBox controls to create an array, and then press F5 and click the picture to view the animation.

Private 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 graphics at same spot.

Next I

FileCab(1).Visible = False	' Set to invisible.

FileCab(0).Visible = True	' Set to visible.

End Sub

Private Sub FileCab_Click (Index As Integer)

Dim I	' Declare variable.

For I = 0 To 1

' Switch the visibility for both graphics.

FileCab(I).Visible = Not FileCab(I).Visible

Next I

End Sub


Align Property

See Also	Example	Applies To

Returns or sets a value that determines whether an object is displayed in any size anywhere on a form or whether it's displayed at the top, bottom, left, or right of the form and is automatically sized to fit the form's width.

Syntax

object.Align [= number]

The Align property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies how an object is displayed, as described in Settings.

Settings

The settings for number 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 object is on an MDI form.

1	(Default in an MDI form) Top [image] object is at the top of the form, and its width is equal to the form's ScaleWidth property setting.

2	Bottom [image] object is at the bottom of the form, and its width is equal to the form's ScaleWidth property setting.

3	Left [image] object is at the left of the form, and its width is equal to the form's ScaleWidth property setting.

4	Right [image] object is at the right 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 a user changes the size of the form, an object with Align set to 1 or 2 automatically resizes to fit the width of the form.

PictureBox and Data controls are the only standard controls that can be placed on an MDI form.  The internal area of an MDI form is defined by the space not covered by controls.  When an MDI child form is maximized within the parent MDI form, it won't cover any controls.

Use number settings 3 and 4 to align toolbars at the left and right sides of a form or MDI form.  If there are two toolbars in a corner of an MDI form, the top- or bottom-aligned one extends to the corner, taking precedence over the left- or right-aligned one.  Left- and right-aligned objects occupy the internal area on an MDI form, just like top- and bottom-aligned objects.


See Also

Alignment Property

ScaleHeight, ScaleWidth Properties


Align Property Applies To

Data Control

PictureBox Control


Alignment Property

See Also	Applies To

Returns or sets a value that determines the alignment of a CheckBox or OptionButton control, text in a control, or values in a column of a DBGrid control.  Read-only at run time for CheckBox, OptionButton, and TextBox controls.

Syntax

object.Alignment [= number]

The Alignment property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies the type of alignment, as described in Settings.

Settings

For CheckBox and OptionButton controls, the settings for number are:

Setting	Description

0	(Default) Control is left-aligned; control is right-aligned.

1	Control is right-aligned; control is left-aligned.

For Label and TextBox controls, the settings for number are:

Setting	Description

0	(Default) Text is left-aligned.

1	Text is right-aligned.

2	Text is centered.

For a DBGrid column, the settings for number are:

Setting	Description

0	Text is left-aligned.

1	Text is right-aligned.

2	Text is centered.

3	(Default) General [image] Text is left-aligned; numbers are right-aligned.

Remarks

You can display text to the right or left of OptionButton and CheckBox controls.  Text is always left-aligned.

If the MultiLine property setting of a TextBox control is False, the Alignment property is ignored.


 See Also

Align Property


Alignment Property Applies To

CheckBox Control

Column Object

DBGrid Control

Label Control

OptionButton Control

TextBox Control


Archive, Hidden, Normal, System Properties

See Also	Applies To

Return or set a value that determines whether a FileListBox control displays files with Archive, Hidden, Normal, or System attributes.

Syntax

object.Archive [= boolean]
object.Hidden [= boolean]
object.Normal [= boolean]
object.System [= boolean]

The Archive, Hidden, Normal, and System property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies the type of files displayed, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default for Archive and Normal) Displays files with the property's attribute in the FileListBox control.

False	(Default for Hidden and System) Displays files without the property's attribute in the FileListBox control.

Remarks

Use these properties to specify the type of files to display in a FileListBox control, based on standard file attributes used in the operating environment.  Setting any of these properties with code at run time resets the FileListBox control to display only those files with the specified attributes.

For example, in a find-and-replace operation you could 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 could set the Archive property to True to list only those files modified since the previous backup.


See Also

Path Property

Pattern Property


Archive, Hidden, Normal, System Properties Applies To
Archive, Hidden, Normal, System Properties Apply To

FileListBox Control


AutoRedraw Property

See Also	Example	Applies To

Returns or sets the output from a graphics method to a persistent graphic.

Syntax

object.AutoRedraw [= boolean]

The AutoRedraw property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies how the object is repainted, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	Enables automatic repainting of a Form object or PictureBox control.  Graphics and text are written to the screen and to an image stored in memory.  The object doesn't receive Paint events; it's repainted when necessary, using the image stored in memory.

False	(Default) Disables automatic repainting of an object and writes graphics or text 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 following graphics methods: Circle, Cls, Line, Point, Print, and PSet.  Setting AutoRedraw to True automatically redraws the output from these methods in a Form object or PictureBox control when, for example, the object is resized or redisplayed after being hidden by another object.

You can set AutoRedraw in code at run time to alternate between drawing persistent graphics (such as a background or grid) and temporary graphics.  If you set AutoRedraw to False, previous output becomes part of the background screen.  When AutoRedraw is set to False, background graphics aren't 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 text, including the persistent graphic, are erased.  In general, all graphics should be displayed using the Paint event unless AutoRedraw is set to True.

To retrieve the persistent graphic created when AutoRedraw is set to True, use the Image property.  To pass the persistent graphic to a Windows API when AutoRedraw is set to True, use the object's hDC property.

If you set a form's AutoRedraw property to False and then minimize the form, 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.


 See Also

Circle Method

Cls Method

hDC Property

Image Property

Line Method

Paint Event

Point Method

Print Method

PSet Method

ScaleHeight, ScaleWidth Properties


AutoRedraw Property Applies To

Form Object

PictureBox Control


AutoShowChildren Property

See Also	Example	Applies To

Returns or sets a value that determines whether MDI child forms are displayed when loaded.

Syntax

object.AutoShowChildren [= boolean]

The AutoShowChildren property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether MDI child forms are automatically visible, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) MDI child forms are automatically displayed when loaded.

False	MDI child forms aren't automatically displayed when loaded.

Remarks

You can use the AutoShowChildren property to load MDI child forms and leave them hidden until they're displayed using the Show method.


See Also

ActiveForm Property

MDIChild Property


AutoShowChildren Property Applies To

MDIForm Object


AutoSize Property

See Also	Applies To

Returns or sets a value that determines whether a control is automatically resized to display its entire contents.

Syntax

object.AutoSize [= boolean]

The AutoSize property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether the control is resized, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True 	Automatically resizes the control to display its entire contents.

False 	(Default) Keeps the size of the control constant.  Contents are clipped when they exceed the area of the control.


See Also

Alignment Property

Resize Event


AutoSize Property Applies To

Label Control

PictureBox Control


CellSelected Property

See Also	Example	Applies To

Returns a value that determines whether the cell specified by the Col and Row properties (the active cell) is within the Grid control's selected region.

Syntax

object.CellSelected

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The settings for CellSelected property are:

Setting	Description

True	The specified cell is within the selected area.

False	The specified cell isn't within the selected area.

Remarks

You can use this property 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 SHIFT and using the arrow keys.

Use the SelEndCol, SelStartCol, SelEndRow, and SelStartRow properties to determine the selected region.  Use the Col and Row properties to determine the active cell.


See Also

Col, Row Properties

RowColChange Event

SelChange Event

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties


CellSelected Property Applies To

Grid Control


Clip Property

See Also	Example	Applies To

Returns or sets the contents of the cells in a selected region of a Grid control.  Not available at design time.

Syntax

object.Clip [= string]

The Clip property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression containing the cell contents.

Remarks

The string can contain the contents of multiple rows and columns.  In string, 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, the following 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 you put data into a Grid control, only the selected cells are affected.  If there are more cells in the selected region than are described in string, the remaining cells are set to Null.  If there are more cells described in string than in the selected region, the unused portion of string is ignored.


See Also

Chr Function

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Text Property


Clip Property Applies To

Grid Control


ClipControls Property

See Also	Example	Applies To

Returns or sets a value that determines whether graphics methods in Paint events repaint the entire object or only newly exposed areas.  Also determines whether the Microsoft Windows operating environment creates a clipping region that excludes nongraphical controls contained by the object.  Read-only at run time.

Syntax

object.ClipControls

The ClipControls property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies how objects are repainted, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) Graphics methods in Paint events repaint the entire object.  A clipping region is created around nongraphical controls on the form before a Paint event.

False	Graphics methods in Paint events repaint only newly exposed areas.  A clipping region isn't created around nongraphical controls before a Paint event.  Complex forms usually load and repaint faster when ClipControls is set to False.

Remarks

Clipping is the process of determining which parts of a form or container, such as a Frame or PictureBox control, are painted when the form is displayed.  An outline of the form and controls is created in memory.  The Windows operating environment uses this outline to paint some parts, such as the background, without affecting other parts, such as the contents of a TextBox control.  Because 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 doesn't clip around the Image, Label, Line, or Shape controls.

Avoid nesting intrinsic controls with ClipControls set to True inside a control with ClipControls set to False (for instance, a command button inside a picture box).  This kind of control nesting causes the controls to repaint incorrectly.  To fix this problem, set the ClipControls property for both the container control and the nested controls to True.


 See Also

AutoRedraw Property

Circle Method

Line Method

Paint Event

Print Method


ClipControls Property Applies To

Form Object

Frame Control

PictureBox Control


ColAlignment Property

See Also	Example	Applies To

Returns or sets the alignment of data in a column.  Not available at design time.

Syntax

object.ColAlignment(column) [= number]

The ColAlignment property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

column	The number of a column.

number	An integer that specifies the column alignment, as described in Settings.

Settings

The settings for number are:

Setting	Description

0	(Default) Left-aligned.

1	Right-aligned.

2	Centered.

Remarks

Any column can have an alignment that is different from other columns.  This property doesn't affect cells in a fixed column.  To set the alignment for a fixed column, use the FixedAlignment property.


See Also

Alignment Property

FixedAlignment Property


ColAlignment Property Applies To

Grid Control


Color Property

See Also	Applies To

Returns or sets the selected color.

Syntax

object.Color [= number]

The Color property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that specifies the color.

Settings

The settings for number 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 in the Visual Basic (VB) object library in the Object Browser.  The Microsoft Windows operating environment substitutes the user's choices, as specified by the user's Control Panel settings.

Remarks

For this property to return a color in a Color dialog box, the RGBInit flag must be set.  In the Font dialog box, the Effects flag must be set.


See Also

Color Constants

Flags Property (Color Dialog)

QBColor Function

RGB Function


Color Property Applies To

CommonDialog Control (Color Dialog)


ColorMode Property

See Also	Applies To

Returns or sets a value that determines whether a color printer prints output in color or monochrome.  Not available at design time.

Syntax

object.ColorMode [= value]

The ColorMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or integer that specifies the print mode, as described in Settings.

Settings

The settings for value are:

Setting	Value	Description

vbPRCMMonochrome	1	Print output in monochrome (usually shades of black and white).

vbPRCMColor	2	Print output in color.

Remarks

The default value depends on the printer driver and the current printer settings.  Monochrome printers ignore this property.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


ColorMode Property Applies To

Printer Object


Columns Property (ListBox)

See Also	Example	Applies To

Returns or sets a value that determines whether a ListBox control scrolls vertically or horizontally and how the items in the columns are displayed.  If it scrolls horizontally, the Columns property determines how many columns are displayed.

Syntax

object.Columns [= number]

The Columns property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies how a control scrolls and how items are arranged in columns, as described in Settings.

Settings

The settings for number are:

Setting	Description

0	(Default) Items are arranged in a single column and the ListBox scrolls vertically.

1 to n	Items are arranged in snaking columns, filling the first column, then the second column, and so on.  The ListBox scrolls horizontally and displays the specified number of columns.

Remarks

For horizontal-scrolling ListBox controls, the column width is equal to the width of the ListBox divided by the number of columns.

This property can't be set to 0 or changed from 0 at run time [image] that is, you can't change a multiple-column ListBox to a single-column ListBox or a single-column ListBox to a multiple-column ListBox at run time.  However, you can change the number of columns in a multiple-column ListBox at run time.


 See Also

AddItem Method

List Property

ListCount Property

ListIndex Property

RemoveItem Method

TopIndex Property


Columns Property Applies To

ListBox Control


ColWidth Property

See Also	Example	Applies To

Returns or sets the width of the specified column in twips.  Not available at design time.

Syntax

object.ColWidth(column) [= number]

The ColWidth property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

column	The number of a column.

number	A numeric expression that specifies the column width.

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 dragging.


See Also

RowHeight Property


ColWidth Property Applies To

Grid Control


Copies Property

See Also	Applies To

Returns or sets a value that determines the number of copies to be printed.  For the Printer object, not available at design time.

Syntax

object.Copies [= number]

The Copies property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that specifies the number of copies to print.  This value must be an integer.

Remarks

For the Print dialog box, this property returns the number of copies entered by the user in the Copies box.  If the UseDevModeCopies flag is set for the CommonDialog control, this property always returns 1.

For the Printer object, multiple copies may or may not be collated, depending on the printer driver.  Multiple copies of the entire document or multiple copies of each page may be printed.  For printers that don't support collating, set Copies = 1, and then use a loop in code to print multiple copies of the entire document.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Duplex Property

PaperBin Property


Copies Property Applies To

CommonDialog Control

Printer Object


CurrentX, CurrentY Properties

See Also	Applies To

Return or set the horizontal (CurrentX) or vertical (CurrentY) coordinates for the next printing or drawing method.  Not available at design time.

Syntax

object.CurrentX [= x]
object.CurrentY [= y]

The CurrentX and CurrentY properties syntax have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

x	A number that specifies the horizontal coordinate.

y	A number that specifies the vertical coordinate.

Remarks

Coordinates are measured from the upper-left corner of an object.  The CurrentX property setting is 0 at an object's left edge, and the CurrentY property setting is 0 at its top edge.  Coordinates are expressed in twips, or the current unit of measurement 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.


 See Also

Circle Method

Cls Method

DrawMode Property

DrawStyle Property

EndDoc Method

Left, Top Properties

Line Method

NewPage Method

Print Method

PSet Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties


CurrentX, CurrentY Properties Applies To
CurrentX, CurrentY Properties Apply To

Form Object

PictureBox Control

Printer Object


Default Property

See Also	Applies To

Returns or sets a value that determines which CommandButton control is the default command button on a form.

Syntax

object.Default [= boolean]

The Default property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether the command button is the default, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True 	The CommandButton is the default command button.

False 	(Default) The CommandButton isn't the default command button.

Remarks

Only one command button on a form can be the default command button.  When Default is set to True for one command button, it's automatically set to False for all other command buttons on the form.  When the command button's Default property setting is True and its parent form is active, the user can choose the command button (invoking its Click event) by pressing ENTER.  Any other control with the focus doesn't 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 the command button that has the focus instead of the default command button.

For a form or dialog box that supports an irreversible action such as a delete operation, make the Cancel button the default command button by setting its Default property to True.

For OLE container controls, the Default property is provided only for those objects that specifically behave like CommandButton controls.


See Also

Cancel Property


Default Property Applies To

CommandButton Control

OLE Container Control


DeviceName Property

See Also	Applies To

Returns the name of the device a driver supports.

Syntax

object.DeviceName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Each printer driver supports one or more devices [image] for example, HP LaserJet IIISi is a device name.

Note   The effect of properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

hDC Property


DeviceName Property Applies To

Printer Object


DragIcon Property

See Also	Example	Applies To

Returns or sets the icon to be displayed as the pointer in a drag-and-drop operation.

Syntax

object.DragIcon [= icon]

The DragIcon property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

icon	Any code reference 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.

Settings

The settings for icon are:

Setting	Description

(none)	(Default) An arrow pointer inside a rectangle.

Icon	A custom mouse pointer.  You specify the icon by setting 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 filename extension and format.

Remarks

You can use the DragIcon property to provide visual feedback during a drag-and-drop operation [image] for example, to indicate that the source control is over an appropriate target.  DragIcon takes effect when the user initiates a drag-and-drop operation.  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.


 See Also

Drag Method

DragDrop Event

DragMode Property

LoadPicture Function

MousePointer Property


DragIcon Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


DragMode Property

See Also	Example	Applies To

Returns or sets a value that determines whether manual or automatic drag mode is used for a drag-and-drop operation.

Syntax

object.DragMode [= number]

The DragMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies the drag mode, as described in Settings.

Settings

The settings for number are:

Setting	Description

0	(Default) Manual [image] requires using the Drag method to initiate a drag-and-drop operation on the source control.

1	Automatic [image] clicking the source control automatically initiates a drag-and-drop operation.  OLE container controls are automatically dragged only when they don't have the focus.

Remarks

When DragMode is set to 1 (Automatic), the control doesn't respond as usual to mouse events.  Use the 0 (Manual) setting to determine when a drag-and-drop operation begins or ends; you can use this setting to initiate a drag-and-drop operation in response to a keyboard or menu command or to enable a source control to recognize a MouseDown event prior to a drag-and-drop operation.

Clicking while the mouse pointer is over a target object or form during a drag-and-drop operation generates a DragDrop event for the target object.  This ends the drag-and-drop operation.  A drag-and-drop operation may also generate a DragOver event.

Note   While a control is being dragged, it can't 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.


 See Also

DragDrop Event

DragIcon Property

DragOver Event


DragMode Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DirListBox Control

DriveListBox Control

DBCombo Control

DBGrid Control

DBList Control

FileListBox Control

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


DrawMode Property

See Also	Example	Applies To

Returns or sets a value that determines the appearance of output from graphics method or the appearance of a Shape or Line control.

Syntax

object.DrawMode [= number]

The DrawMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies appearance, as described in Settings.

Settings

The settings for number are:

Setting	Description

1	Blackness.

2	Not Merge Pen [image] Inverse of setting 15 (Merge Pen).

3	Mask Not Pen [image] Combination of the colors common to the background color and the inverse of the pen.

4	Not Copy Pen [image] Inverse of setting 13 (Copy Pen).

5	Mask Pen Not [image] Combination of the colors common to both the pen and the inverse of the display.

6	Invert [image] Inverse of the display color.

7	Xor Pen [image] Combination of the colors in the pen and in the display color, but not in both.

8	Not Mask Pen [image] Inverse of setting 9 (Mask Pen).

9	Mask Pen [image] Combination of the colors common to both the pen and the display.

10	Not Xor Pen [image] Inverse of setting 7 (Xor Pen).

11	Nop [image] No operation [image] output remains unchanged.  In effect, this setting turns drawing off.

12	Merge Not Pen [image] Combination of the display color and the inverse of the pen color.

13	Copy Pen (Default) [image] Color specified by the ForeColor property.

14	Merge Pen Not [image] Combination of the pen color and the inverse of the display color.

15	Merge Pen [image] Combination of the pen color and the display color.

16	Whiteness.

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 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 the most predictable results.


See Also

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

BackColor, ForeColor Properties

Xor Operator


DrawMode Property Applies To

Form Object

Line Control

PictureBox Control

Printer Object

Shape Control


DrawStyle Property

See Also	Example	Applies To

Returns or sets a value that determines the line style for output from graphics methods.

Syntax

object.DrawStyle [= number]

The DrawStyle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies line style, as described in Settings.

Settings

The settings for number 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, DrawStyle settings 1 through 4 produce a solid line (the DrawStyle property value isn't changed).  If DrawWidth is set to 1, DrawStyle produces the effect described in the preceding table for each setting.


 See Also

Circle Method

DrawMode Property

DrawWidth Property

FillColor Property

FillStyle Property

BackColor, ForeColor Properties

Line Method

PSet Method


DrawStyle Property Applies To

Form Object

PictureBox Control

Printer Object


Drive Property

See Also	Example	Applies To

Returns or sets the selected drive at run time.  Not available at design time.

Syntax

object.Drive [= drive]

The Drive property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

drive	A string expression that specifies the selected drive.

Remarks

The valid drives for the Drive property include all drives present in or connected to the system when the control is created or refreshed at run time.  The default setting of the Drive property is the current drive.

When reading this property setting, 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 isn't case-sensitive).

Changing the setting for the Drive property invokes a Change event.

Selecting a drive that isn't 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 a zero-length string (""), no drive is selected, and the ListIndex property setting is 1.

Note   The Drive property returns a different value from the ListIndex property, which returns the list box selection.


 See Also

FileName Property

ListIndex Property

Path Property

PathChange Event

Pattern Property

PatternChange Event


Drive Property Applies To

DriveListBox Control


DriverName Property

See Also	Applies To

Returns the name of the driver for a Printer object.

Syntax

object.DriverName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Each driver has a unique name.  For example, the DriverName for several of the Hewlett-Packard printers is HPPCL5MS.  The DriverName is typically the driver's filename without an extension.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

DeviceName Property


DriverName Property Applies To

Printer Object


Duplex Property

Applies To

Returns or sets a value that determines whether a page is printed on both sides (if the printer supports this feature).  Not available at design time.

Syntax

object.Duplex [= value]

The Duplex property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant that specifies the type of printing, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbPRDPSimplex	1	Single-sided printing with the current orientation setting.

vbPRDPHorizontal	2	Double-sided printing using a horizontal page turn.

vbPRDPVertical	3	Double-sided printing using a vertical page turn.

Remarks

With horizontal duplex printing, the top of both sides of the page are at the same end of the sheet.  With vertical duplex printing, the bottom of one page is at the same end of the sheet as the top of the next page.  The following diagram illustrates horizontal and vertical duplex printing:

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may produce an error.  For more information, see the manufacturer's documentation for the specific driver.


Duplex Property Applies To

Printer Object


FileName Property

See Also	Example	Applies To

Returns or sets the path and filename of a selected file.  Not available at design time for the FileListBox control and ProjectTemplate object.

Syntax

object.FileName [=  pathname]

The FileName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pathname	A string expression that specifies the path and filename.

Remarks

When you create the control at run time, the FileName property is set to a zero-length string (""), meaning no file is currently selected.

In the CommonDialog control, you can set the FileName property before opening a dialog box to set an initial filename.

Reading this property returns the currently selected filename 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 zero-length string.

When setting this property:

Including a drive, path, or pattern in the string changes the settings of 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 assign an existing filename).

This property setting can be a qualified network path and filename using the following syntax:

\\servername\sharename\pathname


 See Also

Drive Property

List Property

ListIndex Property

Path Property

PathChange Event

Pattern Property

PatternChange Event


FileName Property Applies To

CommonDialog Control

FileListBox Control

ProjectTemplate Object (Add-In)


FillColor Property

See Also	Example	Applies To

Returns or sets the color used to fill in shapes; FillColor is also used to fill in circles and boxes created with the Circle and Line graphics methods.

Syntax

object.FillColor [ = value]

The FillColor property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant that determines the fill color, as described in Settings.

Settings

The settings for value 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 in the Visual Basic (VB) object library in the Object Browser.  The Microsoft Windows operating environment substitutes the user's choices, as specified by the user's Control Panel settings.

By default, FillColor is set to 0 (Black).

Remarks

Except for the Form object, when the FillStyle property is set to its default, 1 (Transparent), the FillColor setting is ignored.


 See Also

BackColor, ForeColor Properties

Color Constants

FillStyle Property

QBColor Function

RGB Function


FillColor Property Applies To

Form Object

PictureBox Control

Printer Object

Shape Control


FillStyle Property

See Also	Example	Applies To

Grid control [image] Returns or sets a value that determines whether setting the Text property of a Grid causes the value to be displayed in all selected cells.

All other objects [image] Returns or sets the pattern used to fill Shape controls as well as circles and boxes created with the Circle and Line graphics methods.

Syntax

object.FillStyle [= number]

The FillStyle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies the fill style, as described in Settings.

Settings

The number settings for a Grid control are:

Setting	Description

0	Single [image] Changing the Text property affects only the active cell.

1	Repeat [image] Changing the Text property affects all selected cells.

The number settings for other objects 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 set to 1 (Transparent), the FillColor property is ignored, except for the Form object.


 See Also

BorderStyle Property

FillColor Property

Paint Event


FillStyle Property Applies To

Form Object

Grid Control

PictureBox Control

Printer Object

Shape Control


FixedAlignment Property

See Also	Example	Applies To

Returns or sets a value that determines the alignment of data in the fixed cells of a column.  Not available at design time.

Syntax

object.FixedAlignment(column) [= number]

The FixedAlignment property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

column	The number of a column.

number	An integer that specifies alignment, as described in Settings.

Settings

The settings for number are:

Setting	Description

0	(Default) Left-aligned.

1	Right-aligned.

2	Centered.

3	Use the ColAlignment setting for the column specified by column.

Remarks

The FixedAlignment property behaves like the ColAlignment property except that it only affects the alignment of fixed cells.  You can use FixedAlignment to align headings differently from the rest of the columns.


See Also

ColAlignment Property


FixedAlignment Property Applies To

Grid Control


FixedCols, FixedRows Properties

See Also	Example	Applies To

Return or set the total number of fixed columns or fixed rows for a Grid control.  By default, a Grid has one fixed column and one fixed row.

Syntax

object.FixedCols [= number]
object.FixedRows [= number]

The FixedCols and FixedRows property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that specifies the number of fixed columns or rows.

Remarks

A fixed column is a stationary column on the left side of the Grid control.  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 don't move when the other columns or rows in the Grid are scrolled.  You can't 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 control must have at least one nonfixed column and one nonfixed row.  The maximum number of fixed columns or rows allowed in a Grid is one less than the total number of columns or rows.


See Also

Cols, Rows Properties

FixedAlignment Property


FixedCols, FixedRows Properties Apply To

Grid Control


FontCount Property

See Also	Example	Applies To

Returns the number of fonts available for the current display device or active printer.

Syntax

object.FontCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

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.


 See Also

FontName Property

Fonts Property


FontCount Property Applies To

Printer Object

Screen Object


Fonts Property

See Also	Example	Applies To

Returns all font names available for the current display device or active printer.

Syntax

object.Fonts(index)

The Fonts property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer from 0 to FontCount 1.

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.


See Also

FontBold, FontItalic, FontStrikethru, FontUnderline Properties

FontName Property

FontSize Property

TextHeight Method

TextWidth Method


Fonts Property Applies To

Printer Object

Screen Object


GridLines Property

See Also	Example	Applies To

Returns or sets a value that determines whether the lines between cells are visible.

Syntax

object.Gridlines [ = boolean]

The Highlight property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A value that specifies the visibility of grid lines, as described in Settings.

Settings

The settings for boolean are:

Setting 	Description

True 	(Default) Grid lines are visible.

False	Grid lines aren't visible.


See Also

Cols, Rows Properties

GridLineWidth Property


GridLines Property Applies To

Grid Control


hDC Property

See Also	Example	Applies To

Returns a handle provided by the Microsoft Windows operating environment to the device context of an object.

Syntax

object.hDC

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

This property is a Windows operating environment device context handle.  The Windows operating environment manages the system display by assigning a device context for the Printer object and for each form and PictureBox control in your application.  You can use the hDC property to refer to the handle for an object's device context.  This provides a value to pass to Windows API calls.

With a CommonDialog control, this property returns a device context for the printer selected in the Print dialog box when the cdlReturnDC flag is set or an information context when the cdlReturnIC flag is set.

Note   The value of the hDC property can change while a program is running, so don't store the value in a variable; instead, use the hDC property each time you need it.

The AutoRedraw property can cause the hDC property setting to change.  If AutoRedraw is set to True for a form or PictureBox container, hDC acts as a handle to the device context of the persistent graphic (equivalent to the Image property).  When AutoRedraw is False, hDC is the actual hDC value of the Form window or the PictureBox container.  The hDC property setting may change while the program is running regardless of the AutoRedraw setting.


 See Also

AutoRedraw Property

hWnd Property

Icon Property


hDC Property Applies To

Form Object

PictureBox Control

Printer Object


HideSelection Property

Example	Applies To

Returns a value that determines whether selected text appears highlighted when a control loses the focus.

Syntax

object.HideSelection

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The HideSelection property return values are:

Value	Description

True	(Default) Selected text doesn't appear highlighted when the control loses the focus.

False	Selected text appears highlighted when the control loses the focus.

Remarks

You can use this property to indicate which text is highlighted while another form or a dialog box has the focus [image] for example, in a spell-checking routine.


HideSelection Property Applies To

TextBox Control


HighLight Property

See Also	Example	Applies To

Returns or sets a value that determines whether selected cells appear highlighted.

Syntax

object.Highlight [= boolean]

The Highlight property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A value that specifies selected cells' appearance, as described in Settings.

Settings

The settings for boolean are:

Setting 	Description

True 	(Default) Selected cells are highlighted.

False	Selected cells aren't 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 selected.


See Also

Col, Row Properties


HighLight Property Applies To

Grid Control


hWnd Property

See Also	Example	Applies To

Returns a handle to a form or control.

Note   This property is no longer supported for the OLE container control.

Syntax

object.hWnd

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The Microsoft Windows operating environment identifies each form and control in an application by assigning it a handle, or hWnd.  The hWnd property is used with Windows API calls.  Many Windows operating environment functions require the hWnd of the active 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.


 See Also

Declare Statement

hDC Property

Icon Property


hWnd Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

MDIForm Object

OptionButton Control

PictureBox Control

TextBox Control


Image Property

See Also	Example	Applies To

Returns a handle to a persistent graphic; the handle is provided by the Microsoft Windows operating environment.

Syntax

object.Image

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

An object's AutoRedraw property determines whether the repainting of an object occurs with a persistent graphics or through Paint events.  The Windows operating environment identifies an object's persistent graphic 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 the AutoRedraw property.  If AutoRedraw is True and nothing has been drawn, the image displays only the color set by 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 on the Clipboard.  You can't 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 bitmap returned by Image.


See Also

AutoRedraw Property

BackColor Property

DragIcon Property

Paint Event

Picture Property

SavePicture Statement


Image Property Applies To

Form Object

PictureBox Control


ItemData Property

See Also	Example	Applies To

Returns or sets a specific number for each item in a ComboBox or ListBox control.

Syntax

object.ItemData(index) [= number]

The ItemData property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	The number of a specific item in the object.

number	The number to be associated with the specified item.

Remarks

The ItemData property is an array of long integer values with the same number of items as a control's List property.  You can use the numbers associated with each item to identify the items.  For example, you can use an employee's identification number to identify each employee name in a ListBox control.  When you fill the ListBox, also fill the corresponding elements in the ItemData array with the employee numbers.

The ItemData property is often used as an index for an array of data structures associated with items in a ListBox control.

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 isn't 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.


 See Also

AddItem Method

List Property

ListIndex Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property


ItemData Property Applies To

ComboBox Control

ListBox Control


KeyPreview Property

See Also	Example	Applies To

Returns or sets a value that determines whether keyboard events for forms are invoked before keyboard events for controls.  The keyboard events are KeyDown, KeyUp, and KeyPress.

Syntax

object.KeyPreview [= boolean]

The KeyPreview property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies how events are received, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The form receives keyboard events first and then the active control.

False	(Default) The active control receives keyboard events; the form doesn't.

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.

Note   Some controls intercept keyboard events so that the form can't receive them.  Examples include the ENTER key when focus is on a CommandButton control and arrow keys when focus is on a ListBox control.


 See Also

KeyDown, KeyUp Events

KeyPress Event


KeyPreview Property Applies To

Form Object


LargeChange, SmallChange Properties

See Also	Example	Applies To

LargeChange [image] Returns or sets the amount of change to the Value property setting in a scroll bar control (HScrollBar or VScrollBar) when the user clicks the area between the scroll box and scroll arrow.

SmallChange [image] Returns or sets the amount of change to the Value property setting in a scroll bar control when the user clicks a scroll arrow.

Syntax

object.LargeChange [= number]
object.SmallChange [= number]

The LargeChange and SmallChange property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies the amount of change to the Value property.

Remarks

For both properties, you can specify an integer between 1 and 32,767, inclusive.  By default, each property is set to 1.

The Microsoft Windows operating environment automatically sets proportional scrolling increments for scroll bars on Form objects, ComboBox controls, and ListBox controls based on the amount of data in the object.  For the HScrollBar and VScrollBar controls, 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 the HScrollBar and VScrollBar controls with the Max and Min properties.


 See Also

Change Event

Max, Min Properties

Value Property


LargeChange, SmallChange Properties Applies To
LargeChange, SmallChange Properties Apply To

HScrollBar, VScrollBar Controls


LeftCol Property

See Also	Example	Applies To

Returns or sets the leftmost visible column (other than a fixed column) in a grid.  Not available at design time.

Syntax

object.LeftCol [= number]

The LeftCol property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that specifies the number of the leftmost visible column.  Default is 0.

Remarks

You can use the LeftCol property in code to scroll a Grid or DBGrid control programmatically.  Use the TopRow property to determine the topmost visible row in the Grid or DBGrid.


See Also

Col, Row Properties

TopRow Property


LeftCol Property Applies To

DBGrid Control

Grid Control


LinkItem Property

See Also	Example	Applies To

Returns or sets the data passed to a destination control in a DDE conversation with another application.

Syntax

object.LinkItem [= string]

The LinkItem property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression that specifies the data to be passed to the destination control.

Remarks

This property corresponds to the item argument in the standard DDE syntax, with application, topic, and item as arguments.  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, PictureBox, or TextBox control on the form can be the item argument in the application|topic!item string used by the destination.  For example, the following syntax represents a valid reference from Microsoft Excel to a Visual Basic application:

=VizBasicApplication|MyForm!TextBox1

You could enter the preceding syntax for a destination cell in the Microsoft Excel formula bar.

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 TextBox control may be both a source (through its parent form) and destination of the same cell in Microsoft Excel.  When data in a Visual Basic TextBox changes, sending data to Microsoft Excel, the cell in Microsoft Excel changes, sending the change to the TextBox, 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, avoiding use of a single item as both destination and source.  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 re-establish the conversation.


 See Also

LinkMode Property

LinkTopic Property


LinkItem Property Applies To

Label Control

PictureBox Control

TextBox Control


LinkMode Property

See Also	Example	Applies To

Returns or sets 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 by 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 by the destination application's application|topic!item expression.

Syntax

object.LinkMode [= number]

The LinkMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	An integer that specifies the type of connection, as described in Settings.

Settings

For controls used as destinations in DDE conversations, the settings for number are:

Setting	Description

0	(Default) None [image] No DDE interaction.

1	Automatic [image] Destination control is updated each time the linked data changes.

2	Manual [image] Destination control is updated only when the LinkRequest method is invoked.

3	Notify [image] 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 settings for number are:

Setting	Description

0	(Default) None [image] 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 can't change it to 1 (Source) at run time.

1	Source [image] Allows any Label, PictureBox, or TextBox control 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, PictureBox, or TextBox control on the form.  If LinkMode is 1 (Source) at design time, you can change it to 0 (None) and back at run time.

Remarks

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, PictureBox, or TextBox control 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.  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 control's LinkMode setting changes to 0 (None).

If you leave LinkMode for a form set to the default 0 (None) at design time, you can't 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 re-establish the conversation.


 See Also

LinkClose Event

LinkError Event

LinkExecute Event

LinkExecute Method

LinkItem Property

LinkNotify Event

LinkOpen Event

LinkRequest Method

LinkSend Method

LinkTimeout Property

LinkTopic Property


LinkMode Property Applies To

Form Object

Label Control

MDIForm Object

PictureBox Control

TextBox Control


LinkTimeout Property

See Also	Applies To

Returns or sets the amount of time a control waits for a response to a DDE message.

Syntax

object.LinkTimeout [= number]

The LinkTimeout property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that specifies the wait time.

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.  If you use LinkTimeout, you can avoid generating a Visual Basic error if a given source application takes too long to respond.

Note   The maximum length of time that a control can wait is 65,535 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.


 See Also

LinkClose Event

LinkItem Property

LinkMode Property

LinkOpen Event

LinkSend Method

LinkTopic Property


LinkTimeout Property Applies To

Label Control

PictureBox Control

TextBox Control


Locked Property

See Also	Applies To

Returns or sets a value indicating whether a control can be edited.

Syntax

object.Locked [ = boolean]

The Locked property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether the control can be edited, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	TextBox control [image] you can scroll and highlight the text in the control, but you can't edit it.  The program can still modify the text by changing the Text property.

Column object [image] you can't edit the values in the column.

False	TextBox control [image] you can edit the text in the control.

Column object [image] you can edit the values in the column.

Remarks

For the Column object, the default setting of Locked is the value of the DataUpdatable property for the underlying field; however, if Column is unbound or the data source doesn't support DataUpdatable, the default is True.  If DataUpdatable in the underlying field is False, you do not create an error by setting this property to True.  However, an error will occur when the control attempts to write the changed data to the database.


 See Also

DataUpdatable Property

ReadOnly Property


Locked Property Applies To

Column Object

TextBox Control


ReadOnly Property

See Also	Applies To

Returns or sets a value indicating whether an object can be edited.

Syntax

object.ReadOnly [ = boolean]

The ReadOnly property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether the control can be edited, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	Data control [image] the control's Database object is opened with read-only access to data.  Changes to the data aren't allowed.

FileListBox control [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.

FileListBox control [image] no read-only files are listed in the control.


ReadOnly Property Applies To

Data Control

FileListBox Control


 See Also

Database Object

Locked Property


Align Property Example

This example uses a PictureBox control as a toolbar on an MDIForm object, with a CommandButton control to move the PictureBox from the top to the bottom of the form.  To try this example, create a new MDIForm and set the MDIChild property of Form1 to True.  Draw a PictureBox on the MDIForm, and put a CommandButton on the PictureBox.  Paste the code into the Declarations section of the MDIForm, and then press F5.  Click the CommandButton to move the PictureBox.

Private 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


AutoRedraw Property Example

This example alternately displays two graphics on a PictureBox control: a persistent filled circle and temporary vertical lines.  Click the PictureBox to draw or redraw the lines.  Resizing the form requires the temporary graphic to be redrawn.  To try this example, paste the code into the Declarations section of a form that has a PictureBox control named Picture1.  Press F5 to run the program, and click the graphic each time you resize the form.

Private 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

Private 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


AutoShowChildren Property Example

This example presents an MDIForm object with an MDI child form, uses the AutoShowChildren property to create a hidden form as another instance of the MDI child form, and then creates a visible MDI child form.  To try this example, set the MDIChild property to True on Form1, and then create an MDIForm with the MDI Form command on the Insert menu.  Copy the code into the Declarations section of the MDIForm, and then press F5 to run the program.

Private Sub MDIForm_Load()

MDIForm1.AutoShowChildren = False	' Set to hide child forms.

Dim HideForm As New Form1	' Declare new form.

HideForm.Caption = "HideForm"	' Set its caption.

Load HideForm	' Load it; it's hidden.

MDIForm1.AutoShowChildren = True	' Set to show child forms.

Dim ShowForm As New Form1	' Declare another new form.

ShowForm.Caption = "ShowForm"	' Set its caption.

Load ShowForm	' Load it; it's displayed.

End Sub


CellSelected Example

This example selects a cell at random and displays a message that tells you whether it's selected or not when the Grid control is clicked.  To try this example, use the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control) to add GRID16.OCX or GRID32.OCX to the project, paste the code into the Declarations section of a new form, and then draw a Grid control and a Label control.  For the Label, set  the AutoSize property to True.  Press F5 to run the program.

Dim TRow As Integer

Dim TCol As Integer

Private 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

Private Sub Grid1_Click ()

Grid1.Row = TRow

Grid1.Col = TCol

' Display message indicating whether clicked cell is selected.

If Grid1.CellSelected Then	' If clicked cell selected,

Label1.Caption = "You found it!"	' message displayed.

Else

Label1.Caption = "Not yet. Try again."

End If

End Sub


Clip Property Example

This example displays the current date and time in the selected area of the Grid control when the user clicks the form.  To try this example, use the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control) to add GRID16.OCX or GRID32.OCX 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.

Private Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

End Sub

Private 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


ClipControls Property Example

This 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, and 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 set ClipControls to False, and then run the program again.  Notice that only newly exposed parts of the form are repainted.

Private Sub Form_Paint ()

' Select a random color for the background.

BackColor = &HFFFFFF * Rnd

End Sub


ColAlignment Property Example

This example fills a Grid control with the letter m and then sets the column alignment to right-aligned for every other column.  To try this example, use the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control) to add GRID16.OCX or GRID32.OCX to the project, and then draw a Grid on a new form.  Press F5 to run the program.

Private Sub Form_Load ()

' Set Cols and Rows.

Grid1.Cols = 5

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


Columns Property Example

This example illustrates how the two different kinds of ListBox controls work when they contain the same data.  To try this example, paste the code into the Declarations section of a form that contains two ListBox controls.  Set the Columns property to 2 for List2, and then press F5 and click the form.

Private 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


ColWidth Property Example

This example enables 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 GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control.

Private Sub Form_Load ()

' Set columns and rows.

Grid1.Cols = 6

Grid1.Rows = 8

End Sub

Private 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


DragIcon Property Example

This example changes the DragIcon property setting each time you drag a PictureBox control.  To try this example, paste the code into the Declarations section of a form that contains a PictureBox control.  Set the DragMode property = 1, and then press F5 and click and drag the PictureBox control.

Private 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 Example

This example enables and disables the ability to drag a CommandButton control each time a form is clicked.  To try this example, paste the code into the Declarations section of a form that contains a CommandButton, and then press F5 and click the form.

Private Sub Form_Click ()

If Command1.DragMode = 0 Then	' Check DragMode.

Command1.DragMode = 1	' Turn it on.

Else

Command1.DragMode = 0	' Or turn it off.

End If

End Sub


DrawMode Property Example

This example enables drawing on a form by dragging the mouse pointer.  Each mouse click sets a different value for the DrawMode property.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private Sub Form_Load

DrawWidth = 10	' Set DrawWidth.

End Sub

Private 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

Private Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

If Button Then	' While button is pressed,

PSet (X, Y)	' draw a big point.

End If

End Sub


DrawStyle Property Example

This example draws seven lines across a form, with each line displaying a different DrawStyle property.  (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, and then press F5 and click the form.

Private 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


Drive Property Example

This 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 DriveListBox control, a DirListBox control, and a FileListBox control, and then press F5.  Use the mouse to change the drive or directory.

Private Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' When drive changes, set directory path.

End Sub

Private Sub Dir1_Change ()

File1.Path = Dir1.Path	' When directory changes, set file path.

End Sub


FileName Property Example

This example displays a message in a Label control when a filename in a FileListBox control is double-clicked.  To try this example, paste the code into the Declarations section of a form that contains a Label control, a DirListBox control, and a FileListBox control, and then press F5 and double-click any filename in the FileListBox control.

Private Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set File1 path.

End Sub

Private Sub File1_PathChange ()

Dir1.Path = File1.Path	' Set Dir1 path.

End Sub

Private Sub File1_DblClick ()

' Display the selected filename when double-clicked.

Label1.Caption = "Your selection: " + UCase(File1.FileName)

End Sub


FillColor Property Example

This example constructs a circle on your form with random FillColor and FillStyle property settings as you click the mouse.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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


FillStyle Property Example

This example displays a circle on a form with random FillColor and FillStyle property settings as you click the mouse.  To try this example, paste the code into the Declarations section, and then press F5 to run the program.

Private 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


FixedAlignment Property Example

This example creates a spreadsheet with centered column headings and row numbers.  To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control.  Press F5 to run the program.

Private 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 and 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 Example

This example illustrates a Grid control with two fixed rows and two fixed columns.  To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid.  To run the program, press F5.

Private 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


FontCount Property Example

This example prints a list of the printer fonts in a ListBox control.  To try this example, paste the code into the Declarations section of a form that has a ListBox control named List1, and then press F5 and click the form.

Private 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


Fonts Property Example

This example prints a list of the printer fonts in a ListBox control.  To try this example, paste the code into the Declarations section of a form that has a ListBox control named List1.  Press F5 to run the program, and then click the form.

Private 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


GridLines Property Example

This example turns the GridLines property on and off as you click the form.  To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control.  Copy the code into the Declarations section, and then press F5 to run the program.

Private Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Private Sub Form_Click ()	' Toggle gridlines on and off.

Grid1.GridLines = Not Grid1.GridLines

End Sub


hDC Property Example

This example draws a triangle and then uses a Microsoft Windows function to fill it with color.  To try this example, create a new module using the Module command on the Insert menu.  Paste the Declare statement into the Declarations section of the new module, being sure that the statement is on one line with no break or wordwrap.  Then paste the Sub procedure into the Declarations section of a form.  Press F5 and click the form.

' Declaration of a Windows routine. This statement is for the module.

Declare Sub FloodFill Lib "GDI" (ByVal hDC As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal Color As Long)

' The following code is for the form.

Private 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


HideSelection Property Example

This example enables you to select text in each form and switch the focus between forms by clicking each form's title bar.  The selection remains visible even when the form isn't active.  To try the example, create two forms and draw a TextBox control on each.  Set the MultiLine property to True for both TextBox controls, and set the HideSelection property to False for one of the TextBox controls.  Paste the code into the Declarations section of both form modules, and then press F5.

Private Sub Form_Load ()

Open "README.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


HighLight Property Example

This example turns highlighting on and off as you click the form.  To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control.  Copy the code into the Declarations section, and then press F5 to run the program.

Private Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Private Sub Form_Click ()	' Toggle highlighting on and off.

Grid1.HighLight = Not Grid1.HighLight

End Sub


hWnd Property Example

This 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.  Create a menu for the form that contains the command Topmost (mnuTopmost).  Create a new module using the Module command on the Insert menu.  Paste the Declare statement into the Declarations section of the new module, being sure that the statement is on one line with no break or wordwrap.  Then paste the Sub procedure into the Declarations section of the form, and press F5.  (This example requires Microsoft Windows version 3.1.)

' Declaration of a Windows routine. This statement is for the module.

Declare Sub SetWindowPos Lib "User" (ByVal hWnd As Integer, ByVal hWndInsertAfter As Integer, ByVal x As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer)

' Set some constant values (from WINAPI.TXT).

Const conHwndTopmost = -1

Const conHwndNoTopmost = -2

Const conSwpNoActivate = &H10

Const conSwpShowWindow = &H40

Private Sub mnuTopmost_Click ()

' Add or remove the check mark from the menu.

mnuTopmost.Checked = Not mnuTopmost.Checked

If mnuTopmost.Checked Then

' Turn on the TopMost attribute.

SetWindowPos hWnd, conHwndTopmost, 0, 0, 0, 0, conSwpNoActivate Or conSwpShowWindow

Else

' Turn off the TopMost attribute.

SetWindowPos hWnd, conHwndNoTopmost, 0, 0, 0, 0, conSwpNoActivate Or conSwpShowWindow

End If

End Sub

This example automatically drops down the list portion of a ComboBox control whenever the ComboBox receives the focus.  To try this example, create a new form containing a ComboBox control and an OptionButton control (used only to receive the focus).  Create a new module using the Module command on the Insert menu.  Paste the Declare statement into the Declarations section of the new module, being sure that the statement is on one line with no break or wordwrap.  Then paste the Sub procedure into the Declarations section of the form, and press F5.  Use the TAB key to move the focus to and from the ComboBox.

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

Private Sub Combo1_GotFocus ()

Const CB_SHOWDROPDOWN = WM_USER + 15

Dim Tmp

Tmp = SendMessage(Combo1.hWnd, CB_SHOWDROPDOWN, 1, ByVal 0&)

End Sub


Image Property Example

This example draws a circle in the first PictureBox control each time you click it.  When you click the second PictureBox, the graphic from the first PictureBox is copied into it.  To try this example, paste the code into the Declarations section of a form that has two large, equal-sized PictureBox controls.  Press F5 to run the program, and then click the PictureBox controls.

Private Sub Form_Load ()

Picture1.AutoReDraw = True	' Set AutoRedraw to True.

End Sub

Private 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

Private Sub Picture2_Click ()

Picture2.Picture = Picture1.Image	' Copy Image to Picture2.

End Sub


ItemData Property Example

This example fills a ListBox control with employee names and fills the ItemData property array with employee numbers using the NewIndex property to keep the numbers synchronized with the sorted list.  A Label control 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 ListBox and a Label.  Set the Sorted property for the ListBox to True, and then press F5 and click the ListBox.

Private 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

Private 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


{bmr copyprnt.mrb}KeyPreview Property Example
KeyPreview Property Example

This example creates a form keyboard handler in the KeyDown event.  Each of the first four function keys displays a different message.  To try this example, paste the code into the Declarations section of a form, and then press F5.  Once the program is running, press any one of the first four (F1 [image] F4) function keys.

' Values from the VB object library.

Const vbKeyF1 = &H70

Const vbKeyF2 = &H71

Const vbKeyF3 = &H72

Const vbKeyF4 = &H73

Private Sub Form_Load ()

KeyPreview = True

End Sub

Private Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)

Select Case KeyCode

Case vbKeyF1: MsgBox "F1 is your friend."

Case vbKeyF2: MsgBox "F2 could copy text."

Case vbKeyF3: MsgBox "F3 could paste text."

Case vbKeyF4: MsgBox "F4 could format text."

End Select

End Sub


{bmr copyprnt.mrb}LargeChange, SmallChange Properties Example
LargeChange, SmallChange Properties Example

This example uses a scroll bar to move a PictureBox control across the form.  To try this example, paste the code into the Declarations section of a form that contains a small PictureBox control and an HScrollBar control, and then press F5 and click the scroll bar.

Private 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

Private Sub HScroll1_Change ()

' Move picture according to scroll bar.

Picture1.Left = (HScroll1.Value / 100) * ScaleWidth

End Sub


{bmr copyprnt.mrb}LeftCol Property Example
LeftCol Property Example

This example changes the LeftCol property with each click of the form.  To try this example, create a new project, add GRID16.OCX or GRID32.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and select Microsoft Grid Control), and then draw a Grid control.  Copy the code into the Declarations section, and then press F5 to run the program.

Private 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

Private 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


{bmr copyprnt.mrb}LinkItem, LinkMode, LinkTopic Properties Example
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 TextBox control.  To try this example, start Microsoft Excel, open a new worksheet named Sheet1, and put some data in the first column.  In Visual Basic, create a form with a TextBox control.  Paste the code into the Declarations section, and then press F5 to run the program.

Private 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 isn't active.

Text1.LinkMode = 0

' Set the application name and topic name.

Text1.LinkTopic = "Excel|Sheet1"

Text1.LinkItem = "R1C1"	' Set LinkItem.

Text1.LinkMode = 1	' Set LinkMode to Automatic.

Else

' Update the row in the data item.

CurRow = "R" & Row & "C1"

Text1.LinkItem = CurRow	' Set LinkItem.

End If

End Sub


GridLineWidth Property

See Also	Example	Applies To

Returns or sets the width in pixels of the gridlines for a Grid control.

Syntax

object.GridLineWidth [= value]

The GridLineWidth property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the gridline width.  The minimum setting is 1 (default); the maximum setting is 10.


See Also

GridLines Property


GridLineWidth Property Applies To

Grid Control


LinkTopic Property

See Also	Example	Applies To

For a destination control [image] returns or sets the source application and the topic (the fundamental data grouping used in that application).  Use LinkTopic with the LinkItem property to specify the complete data link.

For a source form [image] returns or sets the topic that the source form responds to in a DDE conversation.

Syntax

object.LinkTopic [= value]

The LinkTopic property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression specifying a DDE syntax element.

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, which include application, topic, and item.

Note   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

(Don't use the pipe character [|] or exclamation mark [!].)

Within a Visual Basic application, you use:

application|topic

The exclamation mark for topic is implicit.

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 filename without an 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 the source application [image] for example, a worksheet in Microsoft Excel.

In addition, for a destination control only, you must set the related LinkItem property to specify the item element for the link.  A cell reference, such as R1C1, corresponds to an item in a Microsoft Excel worksheet.

Source Form  To set LinkTopic for a source form, set value 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 also needs to specify:

The application element that the destination application uses, which is either the Visual Basic project filename without the .VBP extension (if you're running your application in the Visual Basic development environment) or the Visual Basic application filename without the .EXE extension (if you're 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 filename was changed by the user.  (EXEName always returns the actual filename of the application on disk; DDE always uses the original name that was specified in the Make EXE dialog box.)

The item element that the destination application uses, which corresponds to the Name property setting for the Label, PictureBox, or TextBox control on the source form.

The following syntax is an example of a valid reference from Microsoft Excel to a Visual Basic application acting as a source:

=VizBasicApplication|FormN!TextBox1

You could enter this reference for a destination cell in the Microsoft Excel formula bar.

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, set LinkMode after you set 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, 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 on 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.


See Also

LinkClose Event

LinkError Event

LinkItem Property

LinkMode Property

LinkOpen Event

LinkSend Method


LinkTopic Property Applies To

Form Object

Label Control

MDIForm Object

PictureBox Control

TextBox Control


Max, Min Properties (Scroll Bar)

See Also	Applies To

Max [image] returns or sets a scroll bar position's maximum Value property setting when the scroll box is in its bottom or rightmost position.

Min [image] returns or sets a scroll bar position's minimum Value property setting when the scroll box is in its top or leftmost position.

Syntax

object.Max [= value]

object.Min [= value]

The Max and Min property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying the maximum or minimum Value property setting, as described in Settings.

Settings

For each property, you can specify an integer between -32,768 and 32,767, inclusive.  The default settings are:

Max [image] 32,767.

Min [image] 0.

Remarks

The Microsoft Windows operating environment automatically sets ranges for scroll bars proportional to the contents of forms, ComboBox controls, and ListBox controls.  For a scroll bar (HScrollBar or VScrollBar) 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 scrolled through.  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 set at the leftmost or topmost position of a horizontal or vertical scroll bar, respectively.


See Also

LargeChange, SmallChange Properties


Max, Min Properties Apply To

HScrollBar, VScrollBar Controls


MaxFileSize Property

See Also	Applies To

Returns or sets the maximum size of the filename opened using the CommonDialog control.

Syntax

object.MaxFileSize [= value]

The MaxFileSize property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the maximum size of the filename in bytes.  The range for this property is 1 [image] 32K.  The default is 256.


MaxFileSize Property Applies To

CommonDialog Control (File Dialog)


See Also

FileName Property


MaxLength Property

See Also	Example	Applies To

Returns or sets a value indicating whether there is a maximum number of characters that can be entered in the TextBox control and, if so, specifies the maximum number of characters that can be entered.

Syntax

object.MaxLength [= value]

The MaxLength property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the maximum number of characters a user can enter in a TextBox control.  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 TextBox controls and a maximum of approximately 32K for multiple-line TextBox controls.  Any number greater than 0 indicates the maximum number of characters.

Remarks

Use the MaxLength property to limit the number of characters a user can enter in a TextBox.

If text that exceeds the MaxLength property setting is assigned to a TextBox 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 TextBox but will affect any subsequent changes to the contents.


See Also

Len Function

MultiLine Property


MaxLength Property Applies To

TextBox Control


MDIChild Property

See Also	Example	Applies To

Returns or sets a value indicating whether a form is displayed as an MDI child form inside an MDI form.  Read only at run time.

Syntax

object.MDIChild

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The MDIChild property settings are:

Setting	Description

True	The form is an MDI child form and is displayed inside the parent MDI form.

False	(Default) The form isn't an MDI child form.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

Use this property when creating a multiple-document interface (MDI) application.  At run time, forms with this property set to True are displayed 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 is displayed like any other form because the form is displayed 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 modal.

The initial size and placement of MDI child forms are controlled by the Microsoft Windows operating environment unless you specifically set them in the Load event 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 isn't loaded.

Note   When running under the graphical environment of Microsoft Windows version 3.0 or later, 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 MDIForm object, including reading or setting properties, causes the form to load and become visible.


See Also

ActiveControl Property

ActiveForm Property

BorderStyle Property

ControlBox Property

Make OLE DLL File Command

MaxButton Property

MinButton Property

WindowList Property


MDIChild Property Applies To

Form Object


MouseIcon Property

See Also	Example	Applies To

Sets a custom mouse icon.

Syntax

object.MouseIcon = LoadPicture(pathname)

object.MouseIcon = picture

The MouseIcon property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pathname	A string expression specifying the path and filename of the file containing the custom icon.

picture	The Picture property of a Form object, PictureBox control, or Image control.

Remarks

The MouseIcon property provides a custom icon that is used when the MousePointer property is set to 99.

Although Visual Basic 4.0 does not create cursor (.CUR) files, you can use the MouseIcon property to load either cursor or icon files.  This provides your program with easy access to custom cursors of any size, with any desired hot spot location.  The 32-bit version of Visual Basic does not load animated cursor (.ANI) files, even though 32-bit versions of Windows support these cursors.


See Also

DragIcon Property

Icon Property

LoadPicture Function

MousePointer Property

Picture Property

SavePicture Statement


MouseIcon Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

PictureBox Control

Screen Object

TextBox Control


MousePointer Property

See Also	Example	Applies To

Returns or sets a value indicating the type of mouse pointer displayed when the mouse is over a particular part of an object at run time.

Syntax

object.MousePointer [= value]

The MousePointer property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the type of mouse pointer displayed, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	(Default) Shape determined by the object.

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, and 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.

13	Arrow and hourglass. (Only available in 32-bit Visual Basic.)

14	Arrow and question mark. (Only available in 32-bit Visual Basic.)

15	Size all. (Only available in 32-bit Visual Basic.)

99	Custom icon specified by the MouseIcon property.

Remarks

You can use this property 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, the mouse pointer may change across the entire screen.  If your application doesn't call the DoEvents function and isn't a 32-bit application, it overrides all MousePointer settings for all controls and other applications.  If your application calls DoEvents, the MousePointer property may temporarily change when over a custom control.


See Also

DragIcon Property

Mouse Pointer Constants

MouseIcon Property

MouseMove Event


MousePointer Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

PictureBox Control

Screen Object

TextBox Control


MultiLine Property

See Also	Applies To

Returns or sets a value indicating whether a TextBox control can accept and display multiple lines of text.  Read only at run time.

Syntax

object.MultiLine

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

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 multiple-line TextBox control wraps text as the user types text extending beyond the text box.

You can also add scroll bars to larger TextBox controls using the ScrollBars property.  If no HScrollBar control (horizontal scroll bar) is specified, the text in a multiple-line TextBox automatically wraps.

Note   On a form with no default button, pressing ENTER in a multiple-line TextBox control moves the focus to the next line.  If a default button exists, you must press CTRL+ENTER to move to the next line.


See Also

Default Property

ScrollBars Property


MultiLine Property Applies To

TextBox Control


MultiSelect Property

See Also	Example	Applies To

Returns or sets a value indicating whether a user can make multiple selections in a FileListBox or ListBox control and how the multiple selections can be made.  Read only at run time.

Syntax

object.MultiSelect

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The MultiSelect property settings are:

Setting	Description

0	(Default) Multiple selection isn't allowed.

1	Simple multiple selection.  A mouse click or pressing the SPACEBAR selects or deselects an item in the list.  (Arrow keys move the focus.)

2	Extended multiple selection.  Pressing SHIFT and clicking the mouse or pressing SHIFT and one of the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW, and RIGHT ARROW) extends the selection from the previously selected item to the current item.  Pressing CTRL and clicking the mouse selects or deselects an item in the list.


See Also

AddItem Method

Clear Method

List Property

ListCount Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property


MultiSelect Property Applies To

FileListBox Control

ListBox Control


NewIndex Property

See Also	Applies To

Returns the index of the item most recently added to a ComboBox or ListBox control.

Syntax

object.NewIndex

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

You can use this property 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 in alphabetic order.  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.

The NewIndex property returns -1 if there are no items in the list or if an item has been deleted since the last item was added.


See Also

AddItem Method

Clear Method

ItemData Property

List Property

ListCount Property

MultiSelect Property

RemoveItem Method

Selected Property

TopIndex Property


NewIndex Property Applies To

ComboBox Control

ListBox Control


Orientation Property

See Also	Applies To

Returns or sets a value indicating whether documents are printed in portrait or landscape mode.  Not available at design time.

Syntax

object.Orientation [= value]

The Orientation property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant that determines the page orientation, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbPRORPortrait	1	Documents are printed with the top at the narrow side of the paper.

vbPRORLandscape	2	Documents are printed with the top at the wide side of the paper.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


Orientation Property Applies To

Printer Object


Page Property

See Also	Example	Applies To

Returns the current page number.

Syntax

object.Page

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Visual Basic keeps a count of pages that have been printed since your application started or since the last time the EndDoc statement was used on the Printer object.  This count starts at one and increases by one if:

You use the NewPage method.

You use the Print method and the text you want to print doesn't fit on the current page.

Note   Graphics methods output that doesn't fit on the page doesn't generate a new page.  The output is clipped to fit the page's printable area.


See Also

EndDoc Method

NewPage Method

Print Method


Page Property Applies To

Printer Object


PaperBin Property

See Also	Applies To

Returns or sets a value indicating the default paper bin on the printer from which paper is fed when printing.  Not available at design time.

Syntax

object.PaperBin [= value]

The PaperBin property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant specifying the default paper bin, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbPRBNUpper	1	Use paper from the upper bin.

vbPRBNLower	2	Use paper from the lower bin.

vbPRBNMiddle	3	Use paper from the middle bin.

vbPRBNManual	4	Wait for manual insertion of each sheet of paper.

vbPRBNEnvelope	5	Use envelopes from the envelope feeder.

vbPRBNEnvManual	6	Use envelopes from the envelope feeder, but wait for manual insertion.

vbPRBNAuto	7	(Default) Use paper from the current default bin.

vbPRBNTractor	8	Use paper fed from the tractor feeder.

vbPRBNSmallFmt	9	Use paper from the small paper feeder.

vbPRBNLargeFmt	10	Use paper from the large paper bin.

vbPRBNLargeCapacity	11	Use paper from the large capacity feeder.

vbPRBNCassette	14	Use paper from the attached cassette cartridge.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Not all of the bin options are available on every printer.  Check the printer documentation for more specific descriptions of these options.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


PaperBin Property Applies To

Printer Object


PaperSize Property

See Also	Applies To

Returns or sets a value indicating the paper size for the current printer.  Not available at design time.

Syntax

object.PaperSize [= value]

The PaperSize property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant specifying the paper size, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbPRPSLetter	1	Letter, 8 1/2 x 11 in.

vbPRPSLetterSmall	2	Letter Small, 8 1/2 x 11 in.

vbPRPSTabloid	3	Tabloid, 11 x 17 in.

vbPRPSLedger	4	Ledger, 17 x 11 in.

vbPRPSLegal	5	Legal, 8 1/2 x 14 in.

vbPRPSStatement	6	Statement, 5 1/2 x 8 1/2 in.

vbPRPSExecutive	7	Executive, 7 1/2 x 10 1/2 in.

vbPRPSA3	8	A3, 297 x 420 mm

vbPRPSA4	9	A4, 210 x 297 mm

vbPRPSA4Small	10	A4 Small, 210 x 297 mm

vbPRPSA5	11	A5, 148 x 210 mm

vbPRPSB4	12	B4, 250 x 354 mm

vbPRPSB5	13	B5, 182 x 257 mm

vbPRPSFolio	14	Folio, 8 1/2 x 13 in.

vbPRPSQuarto	15	Quarto, 215 x 275 mm

vbPRPS10x14	16	10 x 14 in.

vbPRPS11x17	17	11 x 17 in.

vbPRPSNote	18	Note, 8 1/2 x 11 in.

vbPRPSEnv9	19	Envelope #9, 3 7/8 x 8 7/8 in.

vbPRPSEnv10	20	Envelope #10, 4 1/8 x 9 1/2 in.

vbPRPSEnv11	21	Envelope #11, 4 1/2 x 10 3/8 in.

vbPRPSEnv12	22	Envelope #12, 4 1/2 x 11 in.

vbPRPSEnv14	23	Envelope #14, 5 x 11 1/2 in.

vbPRPSCSheet	24	C size sheet

vbPRPSDSheet	25	D size sheet

vbPRPSESheet	26	E size sheet

vbPRPSEnvDL	27	Envelope DL, 110 x 220 mm

vbPRPSEnvC3	29	Envelope C3, 324 x 458 mm

vbPRPSEnvC4	30	Envelope C4, 229 x 324 mm

vbPRPSEnvC5	28	Envelope C5, 162 x 229 mm

vbPRPSEnvC6	31	Envelope C6, 114 x 162 mm

vbPRPSEnvC65	32	Envelope C65, 114 x 229 mm

vbPRPSEnvB4	33	Envelope B4, 250 x 353 mm

vbPRPSEnvB5	34	Envelope B5, 176 x 250 mm

vbPRPSEnvB6	35	Envelope B6, 176 x 125 mm

vbPRPSEnvItaly	36	Envelope, 110 x 230 mm

vbPRPSEnvMonarch	37	Envelope Monarch, 3 7/8 x 7 1/2 in.

vbPRPSEnvPersonal	38	Envelope, 3 5/8 x 6 1/2 in.

vbPRPSFanfoldUS	39	U.S. Standard Fanfold, 14 7/8 x 11 in.

vbPRPSFanfoldStdGerman	40	German Standard Fanfold, 8 1/2 x 12 in.

vbPRPSFanfoldLglGerman	41	German Legal Fanfold, 8 1/2 x 13 in.

vbPRPSUser	256	User-defined

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

Setting a printer's Height or Width property automatically sets PaperSize to vbPRPSUser.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


PaperSize Property Applies To

Printer Object


PasswordChar Property

See Also	Example	AppliesTo

Returns or sets a value indicating whether the characters typed by a user or placeholder characters are displayed in a TextBox control; returns or sets the character used as a placeholder.

Syntax

object.PasswordChar [= value]

The PasswordChar property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression specifying the placeholder character.

Remarks

Use this property to create a password field in a dialog box.  Although you can use any character, most Windows-based applications use the asterisk (*) (Chr(42)).

This property doesn't affect the Text property; Text contains exactly what the user types or what was set from code.  Set PasswordChar to a zero-length string (""), which is the default, to display the actual text.

You can assign any string to this property, but only the first character is significant; all others are ignored.

Note   If the MultiLine Property is set to True, setting the PasswordChar property will have no effect.


See Also

Text Property


PasswordChar Property Applies To

TextBox Control


Pattern Property

See Also	Example	Applies To

Returns or sets a value indicating the filenames displayed in a FileListBox control at run time.

Syntax

object.Pattern [= value]

The Pattern property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression 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 could 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 the Pattern property generates a PatternChange event.


See Also

Archive, Hidden, Normal, System Properties

Drive Property

FileName Property

Path Property

PathChange Event

PatternChange Event


Pattern Property Applies To

FileListBox Control


Port Property

See Also	Example	Applies To

Returns the name of the port through which a document is sent to a printer.

Syntax

object.Port

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The operating system determines the name of the port, such as LPT1: or LPT2:.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


Port Property Applies To

Printer Object


PrevInstance Property

Applies To

Returns a value indicating whether a previous instance of an application is already running.

Syntax

object.PrevInstance

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

You can use this property in a Load event 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 Microsoft Windows operating environment at a time.


PrevInstance Property Applies To

App Object


PrintQuality Property

See Also	Applies To

Returns or sets a value indicating the printer resolution.  Not available at design time.

Syntax

object.PrintQuality [= value]

The PrintQuality property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant specifying printer resolution, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbPRPQDraft	-1	Draft resolution

vbPRPQLow	-2	Low resolution

vbPRPQMedium	-3	Medium resolution

vbPRPQHigh	-4	High resolution

In addition to the predefined negative values, you can also set value to a positive dots per inch (dpi) value, such as 300.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

The default value depends on the printer driver and the current settings of the printer.  The effect of these settings varies among printers and printer drivers.  On some printers, some or all of the settings may produce the same result.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


PrintQuality Property Applies To

Printer Object


RowHeight Property

See Also	Example	Applies To

For a Grid control, returns or sets the height of the specified row (record) in twips.  Not available at design time.

For a DBGrid control, returns or sets the height of all rows in the control.  RowHeight is always in the same unit of measure as the container for the DBGrid control.

Syntax

object.RowHeight[(number)] [= value ]

The RowHeight property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	The number of the row in a Grid control.

value	A numeric expression specifying height.

Remarks

For a Grid control, 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 dragging.


See Also

ColWidth Property

Col, Row Properties


RowHeight Property Applies To

DBGrid Control

Grid Control


ScaleHeight, ScaleWidth Properties

See Also	Example	Applies To

Return or set the number of units for the horizontal (ScaleWidth) and vertical (ScaleHeight) measurement of the interior of an object when using graphics methods or when positioning controls.  For MDIForm objects, not available at design time and read-only at run time.

Syntax

object.ScaleHeight [= value]

object.ScaleWidth [= value]

The ScaleHeight and ScaleWidth property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying the horizontal or vertical measurement.

Remarks

You can use these properties to create a custom coordinate scale for drawing or printing.  For example, the statement ScaleHeight = 100 defines the interior 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 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 MDIForm objects, ScaleHeight and ScaleWidth refer only to the area not covered by PictureBox controls in the form.  Avoid using these properties to size a PictureBox in the Resize event of an MDIForm.


See Also

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

FillColor Property

BackColor, ForeColor Properties

Height, Width Properties

Scale Method

ScaleLeft, ScaleTop Properties

ScaleMode Property


ScaleHeight, ScaleWidth Properties Apply To

Form Object

MDIForm Object

PictureBox Control

Printer Object


ScaleLeft, ScaleTop Properties

See Also	Example	Applies To

Return or set the horizontal (ScaleLeft) and vertical (ScaleTop) coordinates for the left and top edges of an object when using graphics methods or when positioning controls.

Syntax

object.ScaleLeft [= value]

object.ScaleTop [= value]

The ScaleLeft and ScaleTop property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying the horizontal or vertical coordinate.  The default is 0.

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 the ScaleMode property 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 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.


See Also

DrawMode Property

DrawStyle Property

FillColor Property

BackColor, ForeColor Properties

Left, Top Properties

Scale Method

ScaleHeight, ScaleWidth Properties

ScaleMode Property


ScaleLeft, ScaleTop Properties Apply To

Form Object

PictureBox Control

Printer Object


ScaleMode Property

See Also	Example	Applies To

Returns or sets a value indicating the unit of measurement for coordinates of an object when using graphics methods or when positioning controls.

Syntax

object.ScaleMode [= value]

The ScaleMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the unit of measurement, as described in Settings.

Settings

The settings for value 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 the ScaleMode property 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 change to reflect the new coordinates of the current point.


See Also

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Scale Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties


ScaleMode Property Applies To

Form Object

PictureBox Control

Printer Object


ScrollBars Property

See Also	Applies To

Returns or sets a value indicating whether an object has horizontal or vertical scroll bars.  Read only at run time.

Syntax

object.ScrollBars

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

For an MDIForm object, 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 or TextBox control, the ScrollBars property settings are:

Setting	Description

0	(Default) None

1	Horizontal

2	Vertical

3	Both

Remarks

For a TextBox control with setting 1 (Horizontal), 2 (Vertical), or 3 (Both), you must set the MultiLine property to True.

At run time, the Microsoft Windows operating environment automatically implements a standard keyboard interface to allow navigation in TextBox controls with the arrow keys (UP ARROW, DOWN ARROW, LEFT ARROW, and RIGHT ARROW), the HOME and END keys, and so on.

Scroll bars are displayed on an object only if its contents extend beyond the object's borders.  For example, in an MDIForm object, if part of a child form is hidden behind the border of the parent MDI form, a horizontal scroll bar (HScrollBar control) is displayed.  Similarly, a vertical scroll bar (VScrollBar control) is displayed on a Grid control when it can't display all of its rows; a vertical scroll bar appears on a TextBox control when it can't display all of its lines of text.  If ScrollBars is set to False, the object won't have scroll bars, regardless of its contents.


See Also

MultiLine Property

WordWrap Property


ScrollBars Property Applies To

Column Object

Grid Control

MDIForm Object

TextBox Control


SelCount Property

See Also	Applies To

Returns the number of selected items in a ListBox control.

Syntax

object.SelCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

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 selections.


See Also

AddItem Method

List Property

ListIndex Property

MultiSelect Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property


SelCount Property Applies To

ListBox Control


Selected Property

See Also	Applies To

Returns or sets the selection status of an item in a FileListBox or ListBox control.  This property is an array of Boolean values with the same number of items as the List property.  Not available at design time.

Syntax

object.Selected(index) [= boolean]

The Selected property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	The index number of the item in the control.

boolean	A Boolean expression specifying whether the item is selected, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The item is selected.

False	(Default) The item isn't selected.

Remarks

This property is particularly useful when 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.


See Also

AddItem Method

Clear Method

List Property

ListCount Property

ListIndex Property

MultiSelect Property

NewIndex Property

RemoveItem Method

TopIndex Property


Selected Property Applies To

FileListBox Control

ListBox Control


SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

See Also	Applies To

Return or set the first or last 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 last selected row.

SelStartRow [image] the first selected row.

Syntax

object.SelEndCol [= value ]

object.SelStartCol [= value]

object.SelEndRow [= value]

object.SelStartRow [= value]

The SelEndCol, SelStartCol, SelEndRow, and SelStartRow property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying the first or last column or row.

Remarks

You can use these properties to select a specific region of a Grid control from code or to return in 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.

The default value for SelStartCol and SelEndCol is -1.


See Also

Col, Row Properties


SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties Apply To

DBGrid Control (SelEndCol and SelStartCol only)

Grid Control


SelLength, SelStart, SelText Properties

See Also	Example	Applies To

SelLength [image] returns or sets the number of characters selected.

SelStart [image] returns or sets the starting point of text selected; indicates the position of the insertion point if no text is selected.

SelText [image] returns or sets the string containing the currently selected text; consists of a zero-length string ("") if no characters are selected.

These properties aren't available at design time.

Syntax

object.SelLength [= number]

object.SelStart [= index]

object.SelText [= value]

The SelLength, SelStart, and SelText property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying the number of characters selected.  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 ComboBox or TextBox control.

index	A numeric expression specifying the starting point of the selected text, as described in Settings.

value	A string expression containing the selected text.

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.


See Also

ActiveControl Property

ActiveForm Property

Text Property


SelLength, SelStart, SelText Properties Apply To

ComboBox Control

DBCombo Control

TextBox Control


Shape Property

See Also	Example	Applies To

Returns or sets a value indicating the appearance of a Shape control.

Syntax

object.Shape [= value]

The Shape property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the control's appearance, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	(Default) Rectangle

1	Square

2	Oval

3	Circle

4	Rounded Rectangle

5	Rounded Square


See Also

BorderStyle Property


Shape Property Applies To

Shape Control


Shortcut Property

See Also	Applies To

Sets a value that specifies a shortcut key for a Menu object.  Not available at run time.

Remarks

Use this property to provide keyboard shortcuts for menu commands.  You can set this property using the Menu Editor.  For a list of shortcut keys you can use, see the Shortcut list in the Menu Editor.

Note   In addition to shortcut keys, you can also assign access keys to commands, menus, and controls by using an ampersand (&) in the Caption property setting.


See Also

Caption Property

Menu Editor


Shortcut Property Applies To

Menu Object


Stretch Property

See Also	Example	Applies To

Returns or sets a value indicating whether a graphic resizes to fit the size of an Image control.

Syntax

object.Stretch [= boolean]

The Stretch property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the graphic resizes, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The graphic resizes to fit the control.

False	(Default) The control resizes to fit the graphic.

Remarks

If Stretch is set to True, resizing the control also resizes the graphic it contains.


See Also

Image Property

Picture Property


Stretch Property Applies To

Image Control


Style Property

See Also	Applies To

Returns or sets a value indicating the type of combo box and the behavior of its list box portion.  Read only at run time.

Syntax

object.Style

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The Style property settings are:

Setting	Description

0	(Default) Dropdown Combo.  Includes a drop-down list and a text box.  The user can select from the list or type in the text box.

1	Simple Combo.  Includes a text box and a list, which doesn't drop down.  The user can select from the list or type in the text box.  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 is displayed.  Increase the Height property to display 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 text box.  Setting 0 saves space on the form because the list portion closes when the user selects an item.

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.


See Also

Change Event

Click Event

DblClick Event

DropDown Event


Style Property Applies To

ComboBox Control

DBCombo Control


TabStop Property

See Also	Applies To

Returns or sets a value indicating whether a user can use the TAB key to give the focus to an object.

Syntax

object.TabStop [= boolean]

The TabStop property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the object is a tab stop, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) Designates the object as a tab stop.

False	Bypasses the object when the user is tabbing, although the object still holds its place in the actual tab order, as determined by the TabIndex property.

Remarks

This property enables you to add or remove a control from the tab order on a form.  For example, if you're using a PictureBox control to draw a graphic, set its TabStop property to False, so the user can't tab to the PictureBox.


See Also

TabIndex Property


TabStop Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


Title Property

See Also	Applies To

Returns or sets the title of the application that is displayed in the Microsoft Windows Task List.  If changed at run time, changes aren't saved with the application.

Syntax

object.Title [= value]

The Title property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression specifying the title of the application.  The maximum length of value is 40 characters.

Remarks

This property is available at design time in the dialog box for the Make EXE command on the File menu.


See Also

Caption Property


Title Property Applies To

App Object


TopIndex Property

See Also	Example	Applies To

Returns or sets a value that specifies which item in a FileListBox or ListBox control is displayed in the topmost position.  Not available at design time.

Syntax

object.TopIndex [= value]

The TopIndex property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	The number of the list item that is displayed in the topmost position.  The default is 0, or the first item in the list.

Remarks

Use this property to scroll through a FileListBox or ListBox control without selecting an item.

If the Columns property is set to 0 for the ListBox control, the item is displayed at the topmost position if there are enough items below it to fill the visible portion of the list.

If the Columns property setting is greater than 0 for the ListBox control, the item's column moves to the leftmost position without changing its position within the column.


See Also

AddItem Method

Clear Method (Clipboard, ComboBox, ListBox)

Columns Property (ListBox)

List Property

ListCount Property

MultiSelect Property

NewIndex Property

RemoveItem Method

Selected Property


TopIndex Property Applies To

FileListBox Control

ListBox Control


TopRow Property

See Also	Example	Applies To

Returns or sets the topmost row displayed in a Grid control.  Not available at design time.

Syntax

object.TopRow [= value ]

The TopRow property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	The number of the topmost row displayed.

Remarks

You can use this property in code to programmatically read or set the visible top row of the Grid control.  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.


See Also

Col, Row Properties

LeftCol Property


TopRow Property Applies To

DBGrid Control

Grid Control


TwipsPerPixelX, TwipsPerPixelY Properties

See Also	Applies To

Return the number of twips per pixel for an object measured horizontally (TwipsPerPixelX) or vertically (TwipsPerPixelY).

Syntax

object.TwipsPerPixelX

object.TwipsPerPixelY

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Windows API routines generally require measurements in pixels.  You can use these properties to convert measurements quickly without changing an object's ScaleMode property setting.


See Also

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property


TwipsPerPixelX, TwipsPerPixelY Properties Apply To

Printer Object

Screen Object


WindowList Property

See Also	Example	Applies To

Returns or sets a value that determines whether a Menu object maintains a list of the current MDI child windows in an MDIForm object.  Read only at run time.

Syntax

object.WindowList

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The WindowList property settings are:

Setting	Description

True	The Menu object maintains a list of open windows and displays a check mark next to the active window.  Users can click a window name to activate that window.

False	(Default) The Menu doesn't 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 object on a form can have its WindowList property set to True.

When you select the WindowList check box in the Menu Editor for a Menu object, the list of open MDI child windows for the menu you're creating is displayed.


See Also

Caption Property

MDIForm Object

Menu Editor


WindowList Property Applies To

Menu Object


WindowState Property

See Also	Example	Applies To

Returns or sets a value indicating the visual state of a form window at run time.

Syntax

object.WindowState [= value]

The WindowState property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer specifying the state of the object, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	(Default) Normal

1	Minimized (minimized to an icon)

2	Maximized (enlarged to maximum size)

Remarks

Before a form is displayed, the WindowState property is always set to Normal (0), regardless of its initial setting.  This is reflected in the Height, Left, ScaleHeight, ScaleWidth, Top, and Width property 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 the WindowState property in the meantime.


See Also

Load Event

Paint Event

Resize Event


WindowState Property Applies To

Form Object

MDIForm Object


WordWrap Property

See Also	Example	Applies To

Returns or sets a value indicating whether a Label control with its AutoSize property set to True expands vertically or horizontally to fit the text specified in its Caption property.

Syntax

object.WordWrap [= boolean]

The WordWrap property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the Label expands to fit the text, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The text wraps; the Label control expands or contracts vertically to fit the text and the size of the font.  The horizontal size doesn't change.

False	(Default) The text doesn't 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 control 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, set the WordWrap and AutoSize properties to True.

If you want a Label control to expand only horizontally, set WordWrap to False.  If you don't want the Label to change size, set AutoSize to False.

Note   If AutoSize is set to False, the text always wraps, regardless of the size of the Label control or the setting of the WordWrap property.  This may obscure some text because the Label doesn't expand in any direction.


See Also

AutoSize Property

Caption Property


WordWrap Property Applies To

Label Control


X1, Y1, X2, Y2 Properties

See Also	Example	Applies To

Return or set 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.

Syntax

object.X1 [= value]

object.Y1 [= value]

object.X2 [= value]

object.Y2 [= value]

The X1, Y1, X2, and Y2 property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A numeric expression specifying a coordinate.

Remarks

Use these properties to dynamically extend a Line control 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.


See Also

Left, Top Properties

Line Method


X1, Y1, X2, Y2 Properties Apply To

Line Control


GridLineWidth Property Example

This example increments the width of gridlines in a Grid control with each click of the mouse.  To try this example, add GRID.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control on a form.  Paste this code into the Declarations section of the form, and then press F5 to run the program.

Private 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


MaxLength Property Example

This example uses a numeric value in one TextBox control to limit the length of text in another TextBox control.  To try this example, paste the code into the Declarations section of a form that contains two TextBox controls.  Make Text1 fairly large, and then press F5.  Enter a number into Text2 and text into Text1.

Private Sub Text1_Change ()

Text1.MaxLength = Text2.Text

End Sub


MDIChild Property Example

This example creates a second instance of an MDI child form within an MDIForm object.  To try this example, set the MDIChild property to True on Form1, and then create an MDIForm object with the MDI Form command on the Insert menu.  Paste the code into the Declarations section of the MDIForm, and then press F5 to run the program.

Private Sub MDIForm_Load ()

Dim NewForm As New Form1	' Declare new form.

NewForm.Show	' Show new form.

End Sub


MouseIcon Property Example

This example illustrates how the MouseIcon property sets a custom mouse icon.  To try the example, create a ListBox control on a form, and then set the MultiSelect property to 1 or 2.  At run time, select one or more items.  Different icons will appear, depending on whether you selected a single item or multiple items.

Private Sub Form_Load ()

' Put some items in the ListBox.

List1.AddItem "Selection 1"

List1.AddItem "Selection 2"

List1.AddItem "Selection 3"

List1.AddItem "Selection 4"

List1.AddItem "Selection 5"

End Sub

Private Sub List1_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

' Set the custom mouse icon for multiple items.

If List1.SelCount > 1 Then

List1.MouseIcon = LoadPicture("ICONS\COMPUTER\MOUSE04.ICO")

List1.MousePointer = 13

Else	' Set the custom mouse icon for a single item.

List1.MouseIcon = LoadPicture("ICONS\COMPUTER\MOUSE02.ICO")

List1.MousePointer = 13

End If

End Sub


MousePointer Property Example

This example changes the mouse pointer to an hourglass while circles are drawn across the 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.

Private Sub Form_Click ()

Dim I	' Declare variable.

Screen.MousePointer = 11	' Change mouse 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 mouse pointer to normal.

End Sub


MultiSelect Property Example

This example fills a ListBox control with the names of your screen fonts and illustrates how the MultiSelect property affects the behavior of a ListBox.  To try this example, create two ListBox controls and a CommandButton control on a form.  In the first ListBox, set the MultiSelect property to 1 or 2.  At run time, select several items in the first ListBox, and then click the CommandButton.  All selected items are displayed in the second ListBox.  Run the example several times with different settings of the MultiSelect property.  Paste the code into the Declarations section, and then press F5 to run the program.

Private Sub Form_Load ()

Dim I	' Declare variable.

' Fill the list box with screen font names.

For I = 0 To Screen.FontCount - 1

List1.AddItem Screen.Fonts(I)

Next I

End Sub

Private 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


{bmr copyprnt.mrb}Page Property Example
Page Property Example

This example prints three pages of text with the current page number at the top of each page.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private 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


PasswordChar Property Example

This example illustrates how the PasswordChar property affects the way a TextBox control displays text.  To try this example, paste the code into the Declarations section of a form that contains a TextBox, and then press F5 and click the form.  Each time you click the form, the text toggles between an asterisk (*) password character and plain text.

Private Sub Form_Click ()

If Text1.PasswordChar = "" Then

Text1.PasswordChar = "*"

Else

Text1.PasswordChar = ""

End If

End Sub


Pattern Property Example

This example updates a TextBox control with the new pattern selected in a FileListBox control.  The controls are set up so that when the user enters a pattern in the TextBox, such as *.TXT, it's reflected in the FileListBox, much like the interaction you see in a typical File Open dialog box in a Windows-based application.  If a full path such as C:\BIN\*.EXE is entered into the TextBox control, the text is automatically parsed into path and pattern components by the FileListBox control.  To try this example, paste the code into the Declarations section of a form that contains the following controls: a DirListBox, a FileListBox, a TextBox, and a CommandButton.  Press F5 and type a valid file pattern into the TextBox.

Private Sub Form_Load ()

Command1.Default = True	' Set Default property.

End Sub

Private Sub Command1_Click ()

' Text is parsed into path and pattern components.

File1.Filename = Text1.Text

Dir1.Path = File1.Path	' Set directory path.

End Sub

Private Sub File1_PatternChange ()

Text1.Text = File1.Pattern	' Set text to new pattern.

End Sub

Private Sub Dir1_Change

File1.Path = Dir1.Path	' Set file list box path.

End Sub


Port Property Example

This example examines each Printer object in the Printers collection to find one connected to a specific port and makes it the default printer.

Dim P As Object

For Each P In Printers

If P.Port = "LPT2:" Or P.DeviceName Like "*LaserJet*" Then

Set Printer = P

Exit For

End If

Next P


RowHeight Property Example

This 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.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control.  Paste the code into the Declarations section of the form, press F5 to run the program, and then select a cell and click the form.

Private Sub Form_Load ()

Grid1.Rows = 5	' Set columns and rows.

Grid1.Cols = 7

End Sub

Private Sub Form_Click ()

Grid1.RowHeight(Grid1.Row) = 500

End Sub


ScaleHeight, ScaleWidth Properties Example

This 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, and then press F5.  To see the effect, click the form, resize it, and then click it again.

Private 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 Example

This example creates a grid in a PictureBox control and sets coordinates for the upper-left corner to -1, -1 instead of 0, 0.  Every 0.25 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 PictureBox and a Timer control, and then press F5.

Private 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

Private 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 Example

This 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, and 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.

Private Sub Form_Click ()

' Cycle through each of the seven ScaleMode settings.

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


SelLength, SelStart, SelText Properties Example

This example enables the user to specify some text to search for and then searches for 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 TextBox control, and then press F5 and click the form.

Private Sub Form_Load ()

Text1.Text = "Two of the peak human experiences"

Text1.Text = Text1.Text & " are good food and classical music."

End Sub

Private 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 and

Text1.SelLength = Len(Search)	' set selection length.

Else

MsgBox "String not found."	' Notify user.

End If

End Sub

This example shows how the Clipboard object is used in cut, copy, paste, and delete operations.  To try this example, create a form with a TextBox control and use the Menu Editor to create an Edit menu (for each of the commands, set the Caption property = Cut, Copy, Paste, and Delete, respectively; set the Name property = EditCut, EditCopy, EditPaste, and EditDelete, respectively).

Private Sub EditCut_Click ()

' Copy selected text to Clipboard.

ClipBoard.SetText Screen.ActiveControl.SelText

' Delete selected text.

Screen.ActiveControl.SelText = ""

End Sub

Private Sub EditCopy_Click ()

' Copy selected text to Clipboard.

ClipBoard.SetText Screen.ActiveControl.SelText

End Sub

Private Sub EditPaste_Click ()

' Place text from Clipboard into active control.

Screen.ActiveControl.SelText = ClipBoard.GetText ()

End Sub

Private Sub EditDelete_Click ()

' Delete selected text.

Screen.ActiveControl.SelText = ""

End Sub


Shape Property Example

This 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 OptionButton control and a Shape control.  For the OptionButton, set the Index property to 0 to create a control array of one element, and then press F5.  Click each OptionButton to see each different shape.

Private Sub Form_Load ()

Dim I	' Declare variable.

Option1(0).Caption = "Shape #0"

For I = 1 To 5 	' Create five 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

Private Sub Option1_Click (Index As Integer)

Shape1.Shape = Index

End Sub


Stretch Property Example

This example loads an arrow icon from an icons directory into an Image control.  The arrow crawls across the form when the Stretch property is set to True and hops across the form when Stretch is set to False.  To try this example, paste the code into the Declarations section of a form that contains an Image control, a CheckBox control, and a Timer control, and 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 CheckBox, and then click the form again.

Dim ImgW	' Declare variable.

Private 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

Private Sub Form_Click ()

Timer1.Enabled = True	' Turn on the timer.

End Sub

Private 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

Private Sub Check1_Click ()

Image1.Stretch = Check1.Value

End Sub


TopIndex Property Example

This example fills a ListBox control with names of screen fonts and then scrolls through the ListBox when you click the form.  To try this example, paste the code into the Declarations section of a form that contains a ListBox control, and then press F5 and click the form.

Private 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

Private 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


TopRow Property Example

This example changes the TopRow property setting with each click on the form.  To try this example, create a new project, add GRID.OCX using the Custom Controls dialog box (from the Tools menu, choose Custom Controls, and then select Microsoft Grid Control), and then draw a Grid control.  Paste the code into the Declarations section of the form, and then press F5 to run the program.

Private 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

Private 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


WindowList Property Example

This example creates some menu commands, illustrates the WindowList menu functionality, and shows how to enable your users to add new forms to a multiple-document interface (MDI) application.  To try this example, create an MDIForm object with the MDI Form command on the Insert menu.  On Form1, set the MDIChild property to True, and create a menu named File.  Select the WindowList box for the File menu.  On your File menu, create a New command, set its Name property to FileMenu, and set its Index property to 0 to create a control array.  Paste the code into the Declarations section of the form, and then press F5 to run the program.  Choosing the New command on the File menu creates new MDI child forms.  Their names are listed at the bottom of the File menu.

Private 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

Private Sub FileMenu_Click (Index As Integer)

Select Case Index

Case 0	' Select New command.

Dim NewForm As New Form1	' Create a duplicate of Form1.

' Load NewForm and set a unique caption.

NewForm.Caption = "Untitled" & Forms.Count

Case 2	' Select Exit command.

End	' End the program.

End Select

End Sub


WindowState Property Example

This 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 an original 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 so you can see both forms, and then minimize or maximize the form and observe the behavior of Form2.

Private Sub Form_Load ()

Form2.Show	' Show Form2.

End Sub

Private Sub Form_Resize ()

Const MIN = 1

If Form1.WindowState = MIN Then	' If parent form is minimized,

Form2.Visible = False	' hide Form2.

Else	' If parent form isn't minimized,

Form2.Visible = True	' restore Form2.

End If

End Sub


WordWrap Property Example

This example puts text into two Label controls 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 Label controls, and then press F5 and click the form to toggle the WordWrap property setting.

Private 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

Private 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


{bmr copyprnt.mrb}X1, Y1, X2, Y2 Properties Example
X1, Y1, X2, Y2 Properties Example

This example displays 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 control and a Line control, and then press F5 and click the form.

Private 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

Private Sub Form_Click ()

Timer1.Enabled = True	' Start the timer.

End Sub

Private 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 another click.

Line1.X1 = 100

Line1.Y1 = 100

Line1.X2 = 500

Line1.Y2 = 300

Odd = False

End If

End Sub


ActiveControl Property

See Also	Example	Applies To

Returns the control that has the focus.  When a form is referenced, as in ChildForm.ActiveControl, ActiveControl specifies the control that would have the focus if the referenced form were active.  Not available at design time; read-only at run time.

Syntax

object.ActiveControl

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

You can use ActiveControl to access a control's properties or to invoke its methods:  For example, Screen.ActiveControl.Tag = "0".  A run-time error occurs if all controls on the form are invisible or disabled.

Each form can have an active control (Form.ActiveControl), regardless of whether or not the form is active.  You can write code that manipulates the active control on each form in your application even when the form isn't the active form.

This property is especially useful in a multiple-document interface (MDI) application where a button on a toolbar must initiate an action on a control in an MDI child form.  When a user clicks the Copy button on the toolbar, your code can reference the text in the active control on the MDI child form, as in ActiveForm.ActiveControl.SelText.

Note   If you plan to pass Screen.ActiveControl to a procedure, you must declare the argument in that procedure with the clause As Control rather than specifying a control type (As TextBox or As ListBox) even if ActiveControl always refers to the same type of control.


See Also

ActiveForm Property

GotFocus Event

LostFocus Event

Make OLE DLL File Command


ActiveControl Property Applies To

Form Object

MDIForm Object

Screen Object


Appearance Property

See Also	Applies To

Returns or sets the paint style of controls on an MDIForm or Form object at run time.  Read-only at run time.

Important   16-bit versions of OLE controls do not provide this property.

Syntax

object.Appearance

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The Appearance property settings are:

Setting	Description

0	Flat.  Paints controls and forms without visual effects.

1	(Default)  3D.  Paints controls with three-dimensional effects.

Remarks

If set to 1at design time, the Appearance property draws controls with three-dimensional effects.  If the form's BorderStyle property is set to Fixed Double (vbFixedDouble, or 3), the caption and border of the form are also painted with three-dimensional effects.  Setting the Appearance property to 1 also causes the form and its controls to have their BackColor property set to the color selected for Button Face in the Color option of the operating system's Control Panel.

Setting the Appearance property to 1 for an MDIForm object affects only the MDI parent form.  To have three-dimensional effects on MDI child forms, you must set each child form's Appearance property to 1.


See Also

BackColor, ForeColor Properties

BorderStyle Property


Appearance Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Image Control

Label Control

ListBox Control

MDIForm Object

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


Bold Property

See Also	Example	Applies To

Returns or sets the font style of the Font object to either bold or nonbold.

Syntax

object.Bold [= boolean]

The Bold property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the font style, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	Turns on bold formatting.

False	(Default) Turns off bold formatting.

Remarks

The Font object isn't directly available at design time.  Instead you set the Bold property by selecting a control's Font property in the Properties window and clicking the Properties button.  In the Font Style box of the Font dialog box, select either Bold or Bold Italic.  At run time, however, you set Bold directly by specifying its setting for the Font object.


See Also

FontTransparent Property

Italic Property

Name Property

Size Property

StrikeThrough Property

Underline Property

Weight Property


Bold Property Applies To

Font Object


FontTransparent Property

See Also	Example	Applies To

Returns or sets a value that determines whether background text and graphics on a Form or Printer object or a PictureBox control are displayed in the spaces around characters.

Syntax

object.FontTransparent [= boolean]

The FontTransparent property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the state of background text and graphics, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) Permits background graphics and text to show around the spaces of the characters in a font.

False	Masks existing background graphics and text around the characters of a font.

Remarks

Set FontTransparent at design time using the Properties window or at run time using code.  Changing FontTransparent at run time doesn't affect graphics and text already drawn to Form, Printer, or PictureBox.


See Also

Bold Property

Italic Property

Name Property

Size Property

StrikeThrough Property

Underline Property

Weight Property


FontTransparent Property Applies To

Form Object

PictureBox Control

Printer Object


Italic Property

See Also	Example	Applies To

Returns or sets the font style of the Font object to either italic or nonitalic.

Syntax

object.Italic [= boolean]

The Italic property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the font style as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	Turns on italic formatting.

False	(Default) Turns off italic formatting.

Remarks

The Font object isn't directly available at design time.  Instead you set the Italic property by selecting a control's Font property in the Properties window and clicking the Properties button.  In the Font Style box of the Font dialog box, select either Italic or Bold Italic.  At run time, however, you set Italic directly by specifying its setting for the Font object.


See Also

Bold Property

FontTransparent Property

Name Property

Size Property

StrikeThrough Property

Underline Property

Weight Property


Italic Property Applies To

Font Object


LBound Property

See Also	Example	Applies To

Returns the lowest ordinal value of a control in a control array.

Syntax

object.LBound

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The LBound property setting is equal to the Index property value of the first control in the array.  Typically this value is 0 because Visual Basic automatically assigns an Index value of 0 to the first control in a control array.  If you manually change the Index value for the first control in an array to some other value (for example, 1), LBound returns the value you manually assigned to Index (in this example, 1).


See Also

Control Array

Count Property

Index Property

UBound Property


LBound Property Applies To

Control Arrays


Size Property (Font)

See Also	Example	Applies To

Returns or sets the font size used in the Font object.

Syntax

object.Size [= number]

The Size property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying the size of the font in points.

Remarks

Use this property to format text in the font size you want.  The default font size is determined by the operating system.  To change the default, specify the size of the font in points.  The maximum value for the Size property is 2048 points.

The Font object isn't directly available at design time.  Instead you set the Size property by selecting a control's Font property in the Properties window and clicking the Properties button.  In the Size box of the Font dialog box, select the size you want.  At run time, however, set Size directly by specifying its setting for the Font object.


See Also

Bold Property

FontTransparent Property

Italic Property

Name Property

StrikeThrough Property

Underline Property

Weight Property


Size Property Applies To

Font Object


StartMode Property

See Also	Example	Applies To

Returns or sets a value that determines whether an application starts as a stand-alone project or as an OLE Automation OLE server.  Read-only at run time.

Syntax

object.StartMode

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The StartMode property settings are:

Constant	Value	Description

vbSModeStandalone	0	(Default) Application starts as a stand-alone project.

vbSModeAutomation	1	Application starts as an OLE Automation OLE server.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

At design time, you can set StartMode in the Project Options dialog box to 1 (vbSModeAutomation) to debug an application as if it were started as an OLE Automation OLE server.  But a project's actual StartMode setting is determined by how that application is started at run time, not by its nominal setting in the Project Options dialog box when you create an executable (.EXE) file.

When StartMode is set to 1 and there are no public classes in the project, you must use the End statement or choose End from the Run menu or toolbar to end the application.  If you choose Close from the Control menu, the form closes but the project is still running.


See Also

EXEName Property

HelpFile Property

Path Property

PrevInstance Property

Title Property


StartMode Property Applies To

App Object


StrikeThrough Property

See Also	Example	Applies To

Returns or sets the font style of the Font object to either strikethrough or nonstrikethrough.

Syntax

object.StrikeThrough [= boolean]

The StrikeThrough property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the font style, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	Turns on strikethrough formatting.

False	(Default) Turns off strikethrough formatting.

Remarks

The Font object isn't directly available at design time.  Instead you set the StrikeThrough property by choosing a control's Font property in the Properties window and clicking the Properties button.  In the Font dialog box, select the Strikeout check box.  At run time, however, you set StrikeThrough directly by specifying its setting for the Font object.


See Also

Bold Property

FontTransparent Property

Italic Property

Name Property

Size Property (Font)

Underline Property

Weight Property


StrikeThrough Property Applies To

Font Object


TrackDefault Property

See Also	Applies To

Returns or sets a value that determines whether the Printer object always points to the same printer or changes the printer it points to if you change the default printer setting in the operating system's Control Panel.  Not available at design time.

Syntax

object.TrackDefault [= boolean]

The TrackDefault property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the printer object points to, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) The Printer object changes the printer it points to when you change the default printer settings in the operating system's Control Panel.

False	The Printer object continues to point to the same printer even though you change the default printer settings in the operating system's Control Panel.

Remarks

Changing the TrackDefault property setting while a print job is in progress sends an implicit EndPage statement to the Printer object.


See Also

ColorMode Property

Copies Property

EndDoc Method

PaperBin Property

PrintQuality Property

Height, Width Properties


TrackDefault Property Applies To

Printer Object


Type Property (Picture)

See Also	Example	Applies To

Returns the graphic format of a Picture object.  Not available at design time; read-only at run time.

Syntax

object.Type

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Valuess

The return values for the Type property are:

Constant	Value	Description

vbPicTypeBitmap	1	Bitmap (.BMP files)

vbPicTypeMetafile	2	Metafile (.WMF files)

vbPicTypeIcon	3	Icon (.ICO files)

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.


See Also

Height, Width Properties


Type Property Applies To

Picture Object


UBound Property

See Also	Example	Applies To

Returns the highest ordinal value of a control in a control array.

Syntax

object.UBound

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

UBound is equal to the Index property value of the last control in the array.


See Also

Index Property

LBound Property


UBound Property Applies To

Control Arrays


Underline Property

See Also	Example	Applies To

Returns or sets the font style of the Font object to either underlined or nonunderlined.

Syntax

object.Underline [= boolean]

The Underline property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying the font style, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	Turns on underline formatting.

False	(Default) Turns off underline formatting.

Remarks

The Font object isn't directly available at design time.  Instead you set the Underline property by selecting a control's Font property in the Properties window and clicking the Properties button.  In the Font dialog box, select the Underline check box.  At run time, however, you set Underline directly by specifying its setting for the Font object.


See Also

Bold Property

FontTransparent Property

Italic Property

Name Property

Size Property (Font)

StrikeThrough Property

Weight Property


Underline Property Applies To

Font Object


UseMnemonic Property

See Also	Example	Applies To

Returns or sets a value that specifies whether an ampersand (&) included in the text of the Caption property of the Label control defines an access key.

Syntax

object.UseMnemonic [= boolean]

The UseMnemonic property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the Label control enables an access key, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default) Any ampersand appearing in the text of the Caption property causes the character following the ampersand to become an access key.  The ampersand itself isn't displayed in the interface of the Label control.

False	Any ampersand appearing in the text of the Caption property is displayed as an ampersand in the interface of the Label control.

Remarks

At run time, pressing ALT+ the access key defined in the Label control's Caption property moves focus to the control that follows the Label control in the tab order.


See Also

Caption Property


UseMnemonic Property Applies To

Label Control


Weight Property

See Also	Example	Applies To

Returns or sets the weight of the characters that make up a Font object.

Syntax

object.Weight [= number]

The Weight property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying the weight of the font.

Remarks

The Font object isn't directly available at design time.  You set the Weight property of the Font object by selecting a control's Font property in the Properties window and clicking the Properties button.  You implicitly set the Weight property by selecting an item from the Font Style box in the Font dialog box.  The Regular and Italic settings have a Weight value of 400 (the default), and the Bold and Bold Italic settings have a Weight value of 700.  At run time, however, you set Weight directly by specifying its setting for the Font object.

If you set a Font object's Weight to a value other than 400 or 700 at run time, Visual Basic converts your value to either 400 or 700, depending on which value is closest to the value you set.  The precise ranges are:  Weight > 400 and < 551 converts to 400; Weight > 550 converts to 700.


See Also

Bold Property

FontTransparent Property

Italic Property

Name Property

Size Property (Font)

StrikeThrough Property

Underline Property


Weight Property Applies To

Font Object


ActiveControl Property Example

This example displays the text of the active control.  To try this example, paste the code into the Declarations section of a form that contains TextBox, Label, and CommandButton controls, and then press F5 and click the form.

Private 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

This example shows how you can use the Clipboard object in cut, copy, paste, and delete operations using buttons on a toolbar.  To try this example, put TextBox and CheckBox controls on Form1, and then insert a new MDIForm object.  On the MDI form, draw a PictureBox control, and then draw a CommandButton in the PictureBox.  Set the Index property of the CommandButton 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 MDIForm, and then press F5.  If the CheckBox has the focus, the buttons don't work.

Private 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

Private 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 onto Clipboard.

Clipboard.SetText ActiveForm.ActiveControl.SelText

' Delete selected text.

ActiveForm.ActiveControl.SelText = ""

Case 1	' Copy.

' Copy selected text onto 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


Bold, Italic, Size, StrikeThrough, Underline, Weight Properties Example

This example prints text on a form with each mouse click.  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form twice.

Private Sub Form_Click ()

Font.Bold = Not Font.Bold	' Toggle bold.

Font.StrikeThrough = Not Font.StrikeThrough ' Toggle strikethrough.

Font.Italic = Not Font.Italic	' Toggle italic.

Font.Underline = Not Font.Underline	' Toggle underline.

Font.Size = 16	' Set Size property.

If Font.Bold Then

Print "Font weight is " & Font.Weight & " (bold)."

Else

Print "Font weight is " & Font.Weight & " (not bold)."

End If

End Sub


FontTransparent Property Example

This example prints text on top of a graphic in a PictureBox control.  Put a PictureBox on a form, set its AutoSize property to True, and load its Picture property with the bitmap (.BMP) file WINLOGO.BMP (from the WINDOWS directory).  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form twice.

Private Sub Form_Click ()

' Toggle property.

Picture1.FontTransparent = Not Picture1.FontTransparent

   Picture1.Print "Demo of FontTransparent property."

End Sub


LBound, UBound Properties Example

This example prints the values of these two properties for a control array.  Put an OptionButton control on a form, and set its Index property to 0 (to create a control array).  To try this example, paste the code into the Declarations section of a form, and then press F5 and click the form.

Private Sub Form_Paint ()

Static FlagFormPainted As Integer

If FlagFormPainted <> True Then ' When form is painting for first time,

For i = 1 To 3

Load Option1(i)	' add three option buttons to array.

Option1(i).Top = Option1(i - 1).Top + 350

Option1(i).Visible = True

Next I

For I =  0 to 3	' Put captions on the option buttons.

Option1(i).Caption = "Option #" & CStr(i)

Next I

Option1(0).Value = True	' Select first option button.

FlagFormPainted = True	' Form is done painting.

End If

End Sub

Private Sub Form_Click ()

Print "Control array's Count property is " & Option1().Count

Print "Control array's LBound property is " & Option1().LBound

Print "Control array's UBound property is " & Option1().UBound

End Sub


StartMode Property Example

This example shows one possible effect of setting the StartMode property to 1 (vbSModeAutomation) at design time.  Open a new project.  From the Tools menu, choose the Options command.  On the Project tab, select the StartMode OLE Server option button.  Choose OK to close the Options dialog box.  To try this example, paste the code into the Declarations section of the form, and then press F5 and double-click the Control menu at the left of the forms title bar.

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)

If UnloadMode = vbFormControlMenu And App.StartMode = vbSModeAutomation Then

Msg = "Form will close but application will still be running." & Chr(10)

Msg = Msg + "To terminate application without a public class," & Chr(10)

Msg = Msg + "you must use an End statement."

MsgBox Msg

End If

End Sub


UseMnemonic Property Example

This example reads the setting of the UseMnemonic property of a Label control.  To try this example, paste the code into the Declarations section of a form that contains a Label, and then press F5 and click the form.

Private Sub Form_Click()

If Label1.UseMnemonic And InStr(Label1, "&") Then

MsgBox "The label has an access key character."

ElseIf Label1.UseMnemonic And Not InStr(Label1, "&") Then

MsgBox "The label supports an access key character but doesn't have an ampersand."

Else

MsgBox "The label doesn't support an access key character."

End If

End Sub


Type, Width Properties Example

This example reads the setting of the Type and Width properties of a Picture object in a PictureBox control.  To try this example, paste the code into the Declarations section of a form that contains a PictureBox whose Picture property is set to an icon, and then press F5 and click the form.

Private Sub Form_Click()

If Picture1.Picture.Type = vbPicTypeIcon Then

Print "The graphic in the picture box is an icon."

Else

Print "The Picture property isn't set to an icon."

End If

Print "Width of the graphic in HiMetrics is " & Picture1.Picture.Width

Print "Width of picture box itself in twips is " & Picture1.Width

End Sub


ActiveForm Property

See Also	Example	Applies To

Returns the form that is the active window.  If an MDIForm object is active or is referenced, it specifies the active MDI child form.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Syntax

object.ActiveForm

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

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 a multiple-document interface (MDI) application where a button on a toolbar must initiate an action on a control in an MDI child form.  When a user clicks the 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 MDIForm object can contain one child form that is the active form within the context of the MDI parent form (MDIForm.ActiveForm).  The ActiveForm on the screen isn't necessarily the same as the ActiveForm in the MDI form, such as when a dialog box is active.  For this reason, specify the MDIForm with ActiveForm when there is a chance of a dialog box being the ActiveForm property setting.

Note   When an active MDI child form isn't 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) even if ActiveForm always refers to the same type of form.

The ActiveForm property determines the default value for the ProjectTemplate object.


See Also

Activate, Deactivate Events

Make OLE DLL File Command

MDIChild Property


ActiveForm Property Applies To

ProjectTemplate Object (Add-In)

MDIForm Object

Screen Object


Caption Property

See Also	Example	Applies To

Form [image] determines the text displayed in the Form or MDIForm object's title bar.  When the form is minimized, this text is displayed below the form's icon.

Control [image] determines the text displayed in or next to a control.

MenuLine object [image] determines the text displayed for a Menu control or an object in the MenuItems collection.

For a Menu control, Caption is normally read/write at run time.  But Caption is read-only for menus that are exposed or supplied by Visual Basic to add-ins, such as the MenuLine object.

Syntax

object.Caption [= string]

The Caption property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form associated with the active form module is assumed to be object.

string	A string expression that evaluates to the text displayed as the caption.

Remarks

When you create a new object, its default caption is the default Name property setting.  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 to designate as an access key.  The character is underlined.  Press the ALT key plus the underlined character to move the focus to that control.  To include an ampersand in a caption without creating an access key, include two ampersands (&&).  A single ampersand is displayed in the caption and no characters are underlined.

For a Label control, the caption is limited to 2048 characters.  For forms and all other controls that have captions, the limit is 255 characters.

To display the caption for a form, set the BorderStyle property to either Fixed Single (1 or vbFixedSingle), Sizable (2 or vbSizable), or Fixed Double (3 or vbFixedDouble).  A caption too long for the form's title bar is clipped.  When an MDI child form is maximized within an MDIForm object, the child form's caption is included in the parent form's caption.

Tip   For a label, set the AutoSize property to True to automatically resize the control to fit its caption.


See Also

AutoSize Property

BorderStyle Property

Name Property


Caption Property Applies To

CheckBox Control

CommandButton Control

Data Control

Form Object

Frame Control

Label Control

MDIForm Object

Menu Control

MenuLine Object

OptionButton Control


Checked Property

See Also	Example	Applies To

Returns or sets a value that determines whether a check mark is displayed next to a menu item.

Syntax

object.Checked [= boolean]

The Checked property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether a check mark is displayed next to a menu item.

Settings

The settings for boolean are:

Setting	Description

True	Places a check mark next to a menu item.

False	(Default) Doesn't place a check mark next to a menu item.

Remarks

At design time, you can use the Menu Editor to set Checked to True.  At run time, you can toggle Checked on and off as part of a Click event procedure attached to a Menu control.  You can also set the value of Checked in a startup procedure or in a form's Load event procedure.

For a Menu control, Checked is normally read/write at run time.  But Checked is read-only for menu items that are exposed or supplied by Visual Basic to add-ins, such as the Add-In Manager command on the Add-Ins menu.


See Also

Enabled Property

Load Event

MenuLine Object

Visible Property


Checked Property Applies To

Menu Control

MenuLine Object


Count Property (VB Collections)

See Also	Applies To

Returns the number of objects in a collection.

Syntax

object.Count

The object placeholder is an object expression that evaluates to an object in the Applies To list.

Remarks

You can use this property with a For...Next statement to carry out an operation on the forms or controls in a collection.  For example, the following code moves all controls on a form 0.5 inches to the right (ScaleMode property setting is 1 or vbTwips):

For I = 0 To Form1.Controls.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 Enabled property setting of only the text boxes or the BackColor property setting of only the option buttons.

Note   The Count property of the SelectedComponents collection, which is exposed by Visual Basic to add-ins, is never greater than 1 in Visual Basic version 4.0.


See Also

Count Function

Count Property (Data Access)

Count Property (VB Collections)

MenuLine Object

RecordCount Property


Count Property Applies To

Controls Collection

ControlTemplates Collection

Form Object

Forms Collection

MenuItems Collection

Properties Collection

Printers Collection

SelectedComponents Collection

SelectedControlTemplates Collection


Enabled Property

See Also	Example	Applies To

Returns or sets a value that determines whether a form or control can respond to user-generated events.

Syntax

object.Enabled [= boolean]

The Enabled property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form associated with the active form module is assumed to be object.

boolean	A Boolean expression that specifies whether object can respond to user-generated events.

Settings

The settings for boolean are:

Setting	Description

True	(Default) Allows object to respond to events.

False	Prevents object from responding to events.

Remarks

The Enabled 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 control by setting Enabled to False cancels the countdown set up by the control's Interval property.

For a Menu control, Enabled is normally read/write at run time.  But Enabled is read-only for menu items that are exposed or supplied by Visual Basic to add-ins, such as the Add-In Manager command on the Add-Ins menu.


See Also

Interval Property

MenuLine Object

Visible Property


Enabled Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

ListBox Control

MDIForm Object

Menu Control

MenuLine Object

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control

Timer Control


HelpContextID Property

See Also	Example	Applies To

Returns or sets an associated context number for an object.  Used to provide context-sensitive Help for your application.

Syntax

object.HelpContextID [= number]

The HelpContextID property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.  If object is omitted, the form associated with the active form module is assumed to be object.

number	A numeric expression that specifies the context number of the Help topic associated with object.

Settings

The settings for number are:

Setting	Description

0	(Default) No context number specified.

> 0	An integer specifying a valid context number.

Remarks

For context-sensitive Help on an object in your application, you must assign the same context number to both object and to the associated Help topic when you compile your Help file.

If you've created a Microsoft Windows operating 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 searches for 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 set to 0, then Visual Basic looks in the HelpContextID of the object's container, and then that object's container, and so on.  If a nonzero current context number can't be found, the F1 key is ignored.

For a Menu control, HelpContextID is normally read/write at run time.  But HelpContextID is read-only for menu items that are exposed or supplied by Visual Basic to add-ins, such as the Add-In Manager command on the Add-Ins menu.

Note   Building a Help file requires the Microsoft Windows Help Compiler, which is included with the Visual Basic Professional Edition.


See Also

HelpFile Property

MenuLine Object


HelpContextID Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

ListBox Control

MDIForm Object

Menu Control

MenuLine Object

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control


Index Property (Control Array)

See Also	Example	Applies To

Returns or sets the number that uniquely identifies a control in a control array.  Available only if the control is part of a control array.

Syntax

object[(number)].Index

The Index property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that evaluates to an integer that identifies an individual control within a control array.

Settings

The settings for number are:

Setting	Description

No value	(Default) Not part of a control array.

0 to 32,767	Part of an array.  Specifies an integer greater than or equal to 0 that identifies a control within a control array.  All controls in a control array have the same Name property.  Visual Basic automatically assigns the next integer 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 specify a particular control in the array.  Index must appear as an integer (or a numeric expression evaluating to an integer) in parentheses next to the control array name [image] for example, MyButtons(3).  You can also use the Tag property setting to distinguish one control from another within a control array.

When a control in the array recognizes that an event has occurred, Visual Basic calls the control array's event procedure and passes the applicable Index setting 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.

Although Visual Basic assigns, by default, the next integer available as the value of Index for a new control in a control array, you can override this assigned value and skip integers.  You can also set Index to an integer other than 0 for the first control in the array.  If you reference an Index value in code that doesn't identify one of the controls in a control array, a Visual Basic run-time error occurs.

Note   To remove a control from a control array, change the control's Name property setting, and delete the control's Index property setting.


See Also

Load Statement

Name Property

Tag Property

Unload Statement


Index Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Data Control

DirListBox Control

DriveListBox Control

FileListBox Control

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

Line Control

ListBox Control

Menu Control

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

Timer Control


Name Property

See Also	Applies To

Returns the name used in code to identify a form, control, or data access object.

Syntax

object.Name

The object placeholder represents an object expression that evaluates to an object in the Applies To list.  If object is omitted, the form associated with the active form module is assumed to be object.

Remarks

The default name for new objects is the kind of object plus a unique integer.  For example, the first new Form object is Form1, a new MDIForm object is MDIForm1, and the third TextBox control 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 underline (_) characters but can't include punctuation or spaces.  Forms can't have the same name as another public object such as Clipboard, Screen, or App.  Although the Name property setting can be a keyword, property name, or the name of another object, this can create conflicts in your code.

You can use a form's Name property with the Dim statement at run time to create other instances of the form.  You can't have two forms with the same name at design time.

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.

For the Application object that is exposed or supplied by Visual Basic to add-ins, the Name property setting is always Microsoft Visual Basic.  For a Property object that is exposed or supplied by Visual Basic to add-ins, the Name property setting is the same as the name listed in the Visual Basic (VB) object library in the Object Browser.

Note   Although Visual Basic often uses the Name property setting as the default value for the Caption, LinkTopic, and Text properties, changing one of these properties doesn't affect the others.


See Also

ActiveForm Property

Caption Property

Dim Statement

Index Property (Control Array)

LinkTopic Property

Me Keyword

Text Property


Name Property Applies To

Application Object

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Component Object (Add-In)

Data Control

Database Object

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Font Object

Form Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

Line Control

ListBox Control

MDIForm Object

Menu Control

OLE Container Control

OptionButton Control

PictureBox Control

Property Object

Shape Control

TextBox Control

Timer Control


Parent Property

See Also	Example	Applies To

Returns the form, object, or collection that contains a control or another object or collection.

Syntax

object.Parent

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use the Parent property to access the properties, methods, or controls of an object's parent.  For example:

MyButton.Parent.MousePointer = 4

The Parent property is useful in an application in which you pass objects as arguments.  For example, you could pass a control variable to a general procedure in a module, and use the Parent property to access its parent form.

There is no relationship between the Parent property and the MDIChild property.  There is, however, a parent-child relationship between an MDIForm object and any Form object that has its MDIChild property set to True.


See Also

ActiveControl Property

ActiveForm Property

MDIChild Property

MenuLine Object


Parent Property Applies To

Application Object

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Component Object

ControlTemplate Object, ControlTemplates Collection

Data Control

DirListBox Control

DriveListBox Control

FileControl Object

FormTemplate Object

Frame Control

Grid Control

HScrollBar, VScrollBar Controls

Image Control

Label Control

Line Control

ListBox Control

Menu Control

MenuItems Collection

MenuLine Object

OLE Container Control

OptionButton Control

PictureBox Control

ProjectTemplate Object

Property Object, Properties Collection

SelectedComponents Collection

SelectedControlTemplates Collection

Shape Control

TextBox Control

Timer Control


Path Property

See Also	Example	Applies To

Returns or sets the current path.  Not available at design time.  For the App object, read-only at run time.

Syntax

object.Path [= pathname]

The Path property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pathname	A string expression that evaluates to the path name.

Remarks

The value of the Path property is a string indicating a path, such as C:\OB or C:\WINDOWS\SYSTEM.  For a DirListBox or FileListBox control, the default is the current path when the control is created at run time.  For the App object, Path specifies the path of the project .VBP file when running the application from the development environment or the path of the .EXE file when running the application as an executable file.

Use this property when building an application's file-browsing and manipulation capabilities.  Setting the Path property has effects on a control similar to the MS-DOS chdir command [image] relative paths are allowed with or without a drive specification.  Specifying only a drive with a colon (:) selects the current directory on that drive.

The Path property can also be set to a qualified network path without a drive connection using the following syntax:

\\servername\sharename\path

The preceding syntax changes the Drive property to a zero-length string ("").

Changing the value of Path has these effects:

For a DirListBox control, generates a Change event.

For a FileListBox control, generates a PathChange event.

Note   For DirListBox, the return value of Path is different from that of List(ListIndex), which returns only the selection.


See Also

Archive, Hidden, Normal, System Properties

Change Event

Drive Property

FileName Property

List Property

ListCount Property

ListIndex Property (Control Array)

PathChange Event

Pattern Property

PatternChange Event

ReadOnly Property


Path Property Applies To

App Object

DirListBox Object

FileListBox Control


Zoom Property

See Also	Applies To

Returns or sets the percentage by which printed output is to be scaled up or down.  Not available at design time.

Syntax

object.Zoom [= number]

The Zoom property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression that evaluates to the percentage by which printed output is to be scaled.  The default is 0, which specifies that the printed page appears at its normal size.

Remarks

The Zoom property setting scales the size of the physical page up or down, by a factor of Zoom/100, to the apparent size of the printed output.  For example, a letter-size page printed with Zoom set to 50 contains as much data as a page of the size 17 by 22 inches because the printed text and graphics are scaled to one-half their original height and width.

Note   The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.  For more information, see the manufacturer's documentation for the specific driver.


See Also

Printer Object, Printers Collection


Zoom Property Applies To

Printer Object


Font Property

See Also	Applies To

Returns a Font object.

Syntax

object.Font

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use the Font property of an object to identify a specific Font object whose properties you want to use.  For example, the following code changes the Bold property setting of a Font object identified by the Font property of a TextBox object:

txtFirstName.Font.Bold = True


See Also

Font Object


Font Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Form Object

Frame Control

Grid Control

Label Control

ListBox Control

OptionButton Control

PictureBox Control

Printer Object

TextBox Control


Container Property

See Also	Example	Applies To

Returns or sets the container of a control on a Form.  Not available at design time.

Syntax

Set object.Container [= container]

The Container property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

container	An object expression that evaluates to an object that can serve as a container for other controls, as described in Remarks.

Remarks

The following controls can contain other controls:

Frame control

PictureBox control.


See Also

Frame Control

Parent Property

PictureBox Control


Container Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

DBCombo Control

DBList Control

DIrListBox Control

DriveListBox Control

FileListBox Control

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

Line Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

VScrollBar Control


Object Property

See Also	Applies To

Returns a reference to a property or method of a custom control which has the same name as a property or method automatically extended to the control by Visual Basic.

Syntax

object.Object[.property | .method]

The Object property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

property	Property of the custom control that is identical to the name of a Visual Basic-supplied property.

method	Method of the custom control that is identical to the name of a Visual Basic-supplied method.

Remarks

Visual Basic supplies some or all of a standard set of properties and methods to custom controls in a Visual Basic project.  It is possible for a custom control to define a property or method which has the same name as one of these standard properties or methods.  When this occurs, Visual Basic automatically uses the property or method it supplies instead of the one with the same name defined in the custom control.  The Object property allows you to bypass the Visual Basic-supplied property or method and use the identically named property or method defined in the custom control.

For example, the Tag property is a property supplied to all custom controls in a Visual Basic project.  If a custom control in a project has the name ctlDemo, and you access the Tag property using this syntax:

ctlDemo.Tag

Visual Basic automatically uses the Tag property it supplies.  However, if the custom control defines its own Tag property and you want to access that property, you use the Object property in this syntax:

ctlDemo.Object.Tag

Visual Basic automatically extends some or all of the following properties and methods to custom controls in a Visual Basic project:

Properties
Align	DragIcon	LinkMode	TabIndex
Cancel	DragMode	LinkItem	TabStop
Container	Enabled	LinkTimeout	Tag
DataChanged	Height	LinkTopic	Top
DataField	HelpContextID	Name	Visible
DataSource	Index	Negotiate	WhatsThisHelpID
Default	Left	Parent	Width
Methods
Drag	LinkRequest	SetFocus
LinkExecute	LinkSend	ShowWhatsThis
LinkPoke	Move	ZOrder
If you use a property or method of a custom control and don't get the behavior you expect, check to see if the property or method has the same name as one of those shown in the preceding list.  If the names match, check the documentation provided with the custom control to see if the behavior matches the Visual Basic-supplied property or method.  If the behaviors aren't identical, you may need to use the Object property to access the feature of the custom control that you want.


See Also

Object Property (OLE Container)


Object Property Applies To

CommonDialog Control

DBCombo Control

DBGrid Control

DBList Control

Grid Control


ActiveForm Property Example

This example prints the time on the active child form in an MDIForm object.  To try this example, create an MDIForm, draw a PictureBox control on it and a CommandButton control in the PictureBox.  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 then press F5.

' Copy this code into the MDI form.

Private Sub MDIForm_Load ()

Dim NewForm As New Form1	' Create new instance of Form1.

NewForm.Show

End Sub

' Copy this code into Form1.

Private Sub Command1_Click ()

' Print the time on the active form.

ActiveForm.Print "The time is " & Format(Now, "Long Time")

End Sub

This example shows how you can use the Clipboard object in cut, copy, paste, and delete operations using buttons on a toolbar.  To try this example, put TextBox and CheckBox controls on Form1, and then insert a new MDIForm object.  On the MDIForm, draw a PictureBox control, and then draw a CommandButton control in the PictureBox.  Set the Index property on the CommandButton 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 MDIForm, and then press F5.  If the CheckBox has the focus, the buttons don't work.

Private 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

Private 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


Caption Property Example

This example changes the Caption property of a CommandButton control each time the user clicks the button.  To try this example, paste the code into the Declarations section of a form containing a CommandButton named Command1, and then press F5 and click the button.

Private Sub Command1_Click ()

' Check caption, then change it.

If Command1.Caption = "Clicked" Then

Command1.Caption = "OK"

Else

Command1.Caption = "Clicked"

End If

End Sub


Checked Property Example

This example displays and removes a check mark next to a menu item.  To try this example, create a form with a Menu control that has one menu item (set both the Caption and Name properties to MyMenuItem), and then press F5 and choose the menu item.

Private Sub MyMenuItem_Click ()

' Turn check mark on menu item on and off.

MyMenuItem.Checked = Not MyMenuItem.Checked

End Sub


Enabled Property Example

This example enables a CommandButton control whenever a TextBox control contains text.  To try this example, paste the code into the Declarations section of a form with CommandButton and TextBox controls, and then press F5 and enter something in the text box.

Private Sub Form_Load ()

Text1.Text = ""	' Clear the text box.

Command1.Caption = "Save"	' Put caption on button.

End Sub

Private Sub Text1_Change ()

If Text1.Text = "" Then	' See if text box is empty.

Command1.Enabled = False	' Disable button.

Else

Command1.Enabled = True	' Enable button.

End If

End Sub


HelpContextID Property Example

This example uses topics in the Visual Basic Help file to demonstrate 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 TextBox control and a Frame control with an OptionButton control inside of it.  Press F5.  Once the program is running, move the focus to one of the controls, and press F1.

' Actual context numbers from the Visual Basic Help file.

Const winColorPalette = 21004	' Define constants.

Const winToolbox = 21001

Const winCodeWindow = 21005

Private Sub Form_Load ()

App.HelpFile = "VB.HLP"

Frame1.HelpContextID = winColorPalette

Text1.HelpContextID = winToolbox

Form1.HelpContextID = winCodeWindow

End Sub


Index Property Example

This example starts with two OptionButton controls and adds a new OptionButton to the form each time you click a CommandButton control.  When you click an OptionButton, 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 OptionButton controls (set the Name property to optButton for both buttons to create a control array), a CommandButton, and a large PictureBox control.

Private 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

Private 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 eight 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


Parent Property Example

This example passes a control from a form that doesn't have the focus to a procedure in a module, and then displays the state of the control on the parent form.  To try this example, create three forms: Form1, containing a CommandButton control, and Form2 and Form3, each containing a CheckBox control. 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 this code into Form1.

Private Sub Form_Load ()

Form2.Show	' Display all forms.

Form3.Show

Form2.AutoRedraw = True

Form3.AutoRedraw = True

End Sub

Private Sub Command1_Click ()

ReadCheckBox Form2.Check1	' Call procedure in other module

ReadCheckBox Form3.Check1	' and send control as argument.

End Sub

' Enter this code into Module1.

Sub ReadCheckBox (Source As Control)

If Source.Value Then

Source.Parent.Cls	' Clear parent form.

Source.Parent.Print "CheckBox is ON."  ' Display on parent form.

Else

Source.Parent.Cls	' Clear parent form.

Source.Parent.Print "CheckBox is OFF."  ' Display on parent form.

End If

End Sub


Path Property Example

This 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 DriveListBox, DirListBox, and FileListBox controls.  Press F5.  Use the mouse to change the drive or directory.

Private Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' Set directory path.

End Sub

Private Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set file path.

End Sub


Container Property Example

This example demonstrates moving a CommandButton control from container to container on a Form object.  To try this example, put a Frame control, a PictureBox control and a CommandButton on the Form.  Then run the example.

Private Sub Form_Click()

Static intX As Integer

Select Case intX

Case 0

Set Command1.Container = Picture1

Command1.Top= 0

Command1.Left= 0

Case 1

Set Command1.Container = Frame1

Command1.Top= 0

Command1.Left= 0

Case 2

Set Command1.Container = Form1

Command1.Top= 0

Command1.Left= 0

End Select

intX = intX + 1

End Sub


Visual Basic Menus


Visual Basic Menus

See Also

File Menu

Edit Menu

View Menu

Insert Menu

Run Menu

Tools Menu

Add-Ins Menu

Help Menu


See Also

Visual Basic Help


File Menu

See Also

New Project

Open Project

Save File

Save File As

Save Project

Save Project As

Add File

Remove File

Print Setup

Print

Make EXE File

Make OLE DLL File

Exit


See Also

Visual Basic Help

Visual Basic Menus


Edit Menu

See Also

Undo

Redo

Cut

Copy

Paste

Paste Link

Delete

Find

Replace

Indent

Outdent

Bring To Front

Send To Back

Align To Grid

Lock Controls


See Also

Visual Basic Help

Visual Basic Menus


View Menu

See Also

Code

Form

Procedure Definition

Last Position

Object Browser

Debug Window

Project

Properties

Toolbox

Toolbar

Color Palette


See Also

Visual Basic Help

Visual Basic Menus


Insert Menu

See Also

Procedure

Form

MDI Form

Module

Class Module

File


See Also

Visual Basic Help

Visual Basic Menus


Run Menu

See Also

Start (Break at Run Time, Continue in Break Mode)

Start With Full Compile

Break

End

Restart

Step Into

Step Over

Step To Cursor

Toggle Breakpoint

Clear All Breakpoints

Set Next Statement

Show Next Statement


See Also

Visual Basic Help

Visual Basic Menus


Tools Menu

See Also

Add Watch

Edit Watch

Instant Watch

Calls

Menu Editor

Custom Controls

References

Get

Check Out

Check In

Undo Check Out

Options


See Also

Visual Basic Help

Visual Basic Menus


Add-Ins Menu

See Also

Data Manager

Report Designer

Add-In Manager


See Also

Visual Basic Help

Visual Basic Menus


Help Menu

See Also

Contents

Search for Help On

Obtaining Technical Support

Learning Microsoft Visual Basic

About Microsoft Visual Basic


See Also

Visual Basic Help

Visual Basic Menus


Custom Controls Dialog Box

See Also

Use the Custom Controls dialog box to add custom controls and insertable objects to your project's Toolbox.

To open the Custom Controls dialog box, choose Custom Controls from the Tools menu.

To close the Custom Controls dialog box, double-click the Control-menu box or press the ESC key.  To accept the settings in the Custom Controls dialog box, choose OK.

Dialog Box Options

Available Controls

Displays the available custom controls and insertable objects.

To add a control or insertable object to your Toolbox, select the check box next to its name.

To remove a control or insertable object from your project, clear the check box next to its name.

When you are done making selections, choose OK to update your Toolbox.

Note   You can't remove a control or insertable object that is used in your project.

Path

Displays the path of the item selected in the Available Controls box.

Show

Determines which items are listed in the Available Controls box.  You can select either or both of the following options.

Insertable Objects [image] Displays insertable objects, such as a Microsoft Excel Chart.

Controls [image] Displays controls with .OCX and .VBX filename extensions.

Selected Items Only [image] Displays only those items in the Available Controls list which you have selected to include in the project.

Browse

Displays the Browse dialog box.  To add a VBX or OLE custom control to the Available Controls box, choose the Browse button, and search other directories for files with .VBX and .OCX filename extensions.


See Also

Custom Controls Command (Tools Menu)


References Dialog Box

See Also

Use the References dialog box to make another application's objects available in your code by setting a reference to that application's object library.

To open the References dialog box, choose References from the Tools menu.

To close the References dialog box, double-click the Control-menu box or press the ESC key.  To accept the settings in the References dialog box, choose OK.

Dialog Box Options

Available References

Lists the references available to your project.

To add a reference to your project, select the check box next to its name.  Once you have set a reference to an object library, you can find a specific object and its methods and properties in the Object Browser.

To remove a reference from your project, clear the check box next to its name.  You can't remove a reference for an item that is used in your project.  If you are not using any objects in a referenced library, you should clear the check box for that reference to minimize the number of object references Visual Basic must resolve, thus reducing the time it takes your project to compile.

Note   You can't remove the "Visual Basic for Applications" and "Visual Basic objects and procedures" references, because they are necessary for running Visual Basic.

Priority Buttons

Moves references up and down on the list.  When you refer to an object in code, Visual Basic searches each application selected in the References dialog box in the order the applications are displayed.  If two applications use the same name for an object, Visual Basic uses the definition provided by the application listed higher in the Available References box.

Result

Displays the path of the reference selected in the Available References box, as well as the language version.

Browse

Displays the Browse dialog box.  To add a reference to the Available References box, choose the Browse button, and search other directories for the following file types:

Type Libraries (*.OLB, *.TLB)

Executable Files (*.EXE)

OLE Controls (*.OCX)

All Files (*.*)


See Also

Object Browser

References Command (Tools Menu)


Add-In Manager Dialog Box

See Also

An add-in is an OLE server that adds capabilities to the Visual Basic development environment.  You use the Add-In Manager to add or remove add-ins for your project.

To open the Add-In Manager dialog box, choose Add-In Manager from the Tools menu.

To close the Add-In Manager dialog box, double-click the Control-menu box or press the ESC key.  To accept changes to the Available Add-Ins box, choose OK.

The Available Add-Ins box lists any:

Currently running add-in

Add-in listed in VB.INI

All currently running add-ins are checked in the list box, including those running in other instances of Visual Basic.  It is up to the developer of the add-in to ensure that the add-in is registered in your system registry when you install the add-in; otherwise, it won't appear in this box.

The check box to the left of each name indicates whether that add-in is used by the current project.

To add an add-in to your Visual Basic environment, select the check box.

To remove an add-in, clear the check box.

When your selections are complete, choose OK.  Visual Basic:

Updates VB.INI with your selections

Unloads the deselected add-ins

Loads the selected add-ins

When you add an add-in, it is loaded every time you restart Visual Basic until you remove it.


See Also

Add-In Manager Command (Add-Ins Menu)


Code Window

See Also

Use the Code window to write, display, and edit Visual Basic code.  You can open as many Code windows as you have modules, so you can easily view the code in different form, standard, and class modules, and copy and paste between them.

To open a Code window from the Project window, select a form, class, or standard module, and choose the View Code button.

To open a Code window from a Form window, double-click a control or the form, choose Code from the View menu, or press F7.

The Code window includes:

The Object box.  Displays the name of the selected object.  Click the arrow to the right of the list box to display a list of all objects associated with the form.

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, the event procedure associated with that event name is displayed in the Code window.

If (General) is displayed in the Object box, the Procedure box lists any declarations and 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 Code window.

Note   All procedures in a module are displayed in the same Code window.

The Split bar.  The Split bar is located 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.

You can choose to display procedures in the Code window using either of two views:

Full module view

Single procedure view

Use the Editor Options tab of the Options dialog box to choose between full module view or single procedure view.

Under full module view, all the procedures in the module appear in a single, scrollable list.  The procedures are sorted alphabetically by name.  When using full module view, you can also choose to display a separator line that indicates the end of a procedure.  Selecting a procedure using the drop down list boxes at the top of the Code window moves the cursor to the first line of code in the procedure you select, automatically scrolling the module if necessary.

Under single procedure view, the Code window displays the code for one only procedure at a time.  Selecting a procedure in the drop down list boxes at the top of the Code window displays the selected procedure.

Note   If you need help with 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

Code Command (View Menu)

Code Window Keyboard Shortcuts

Context Menus

Entering and Editing Code

Entering Declarations in Code

Editor Options Tab

Object Browser

Project Window


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 View menu.

To close the Color palette, double-click the Control-menu box or press the ESC key.

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 is 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, and then click the color you want.

To change the background color, click the outer box on the default color box, and 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.

Select a Custom Color color box, and then 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 BackColor or ForeColor property.


See Also

BackColor, ForeColor Properties

Color Palette Command (View Menu)


Debug Window

See Also

The Debug window automatically opens at run time.  In break mode, you can use the Debug window to execute individual lines of code, view or change values of variables and properties, and view watch expressions.  At run time, you can use it to display data or messages as the program runs.  At design time, you can view previous output to the Debug window, but you can't execute code.

To open the Debug window, choose Debug Window from the View menu.

To close the Debug window, double-click the Control-menu box.

Dialog Box Options

Procedure box

During break mode, the Procedure box displays the name of the project, module, and procedure name where execution is stopped.  The button to the right of the Procedure box displays the Calls dialog box.  The Calls dialog box shows a list of all procedures that were started and not completed.

Immediate pane

Displayed by default the first time you open the Debug window.  From break mode, you can execute code immediately by entering it in this pane.  While working in the Immediate pane:

You can type or paste a line of code and press ENTER to run it.

You can execute only one line of code at a time.

You can't save code, but you can copy and paste it into the Code window.

Note   In break mode, a statement in the Immediate pane is executed in the context or scope that is displayed in the Procedure box.  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 occurred in the procedure you were executing when the program halted.

Watch pane

Displays the current watch expressions.  The Watch pane appears automatically if watch expressions are defined in the project.

Expression [image] The watch expression.

Value [image] The value of the expression at the time of the transition to break mode.

Context [image] The context of the watch expression.

If the context of the expression isn't in scope when going to break mode, the current value isn't displayed.

Split bar

Separates the Debug window into two panes.  The upper pane displays the Watch pane.  The lower pane displays the Immediate pane.


See Also

Add Watch Command (Tools Menu)

Add Watch Dialog Box

Adding Watch Expressions

Calls Dialog Box

Code Window

Context Menus

Debug Object

Debug Window Command (View Menu)

Debugging Checklist

Deleting Watch Expressions

Edit Watch Command (Tools Menu)

Editing Watch Expressions

Instant Watch Command

Print Method

Setting and Clearing Breakpoints

Using Instant Watch

Using the Immediate Pane


Environment Options Tab

See Also

Use the Environment tab of the Options dialog box to specify attributes of your Visual Basic development environment.

To open the Environment tab of the Options dialog box, choose Options from the Tools menu, then click the Environment tab.

To close the Options dialog box, double-click the Control-menu box or press the ESC key.  To accept the settings in the Options dialog box, choose OK.

Changes made in this dialog box are saved in the VB.INI file, and are loaded every time you restart Visual Basic.

Tab Options

Form Design Grid

Determines the appearance of the form grid at design time.

Show Grid [image] Determines whether to show the grid at design time.

Width [image] Determines the width of grid cells on a form; 45 to 1,485 twips.

Height [image] Determines the height of grid cells on a form; 45 to 1,485 twips.

Align Controls to Grid [image] Automatically positions the outer edges of controls on grid lines.

Windows On Top

Determines if any of the listed windows should always be displayed frontmost on the desktop when visible.

Show ToolTips

Displays ToolTips for the toolbar and Toolbox buttons.

Require Variable Declaration

Determines whether explicit variable declarations are required in modules. Selecting this adds the Option Explicit statement to general declarations in any new module.

Save Before Run

Determines whether to automatically save all files before running, or to prompt before saving.

Auto Syntax Check

Determines whether Visual Basic should automatically verify correct syntax after you enter a line of code.


See Also

Custom Control Upgrade Dialog Box

Options Command (Tools Menu)


Editor Options Tab

See Also

Use the Editor tab of the Options dialog box to specify the appearance of your Visual Basic code.  It includes a list of the types of text found in code, and boxes in which you can specify attributes for selected text types.

To open the Editor tab of the Options dialog box, choose Options from the Tools menu, then click the Editor tab.

To close the Options dialog box, double-click the Control-menu box or press the ESC key.  To accept the settings in the Options dialog box, choose OK.

Tab Options

Font

Determines the font used for all code.

Size

Determines the size of the font used for code.

Code Colors

Determines the foreground and background colors used for the type of text selected in the list box.

Auto Indent

Allows you to tab the first line of code; all subsequent lines will start at that tab location.

Full Module View

Allows you to look at procedures in the code window either as a single scrollable listing or only at one procedure at a time.

Procedure Separator

Allows you to display or hide separator bars that appear at the end of each procedure in the Code window.

Tab Width

Sets the tab width, which can range from 1 to 32 spaces; the default is 4 spaces.

Sample

Displays sample text for the font, size, and color settings.


See Also

Code Window

Options Command (Tools Menu)

Indent Command (Edit Menu)


Project Options Tab

See Also

Use the Project tab of the Options dialog box to specify settings for the current Visual Basic project.

To open the Project tab of the Options dialog box, choose Project Options from the Tools menu, then click the Project tab.

To close the Options dialog box, double-click the Control-menu box or press the ESC key.  To accept the settings in the Options dialog box, choose OK.

Tab Options

Startup Form

The first form that Visual Basic displays at run time.

Project Name

The project name used as part of the fully qualified name of an item in the project.  Also the name displayed in the Object Browser when a reference is made to a Visual Basic OLE server.

Help File

The name of the Help file associated with the project.

HelpContextID

The context ID for the specific Help topic to be called when the user selects the "?" button while the application's object library is selected in the Object Browser.

StartMode

Indicates how the application is started.  This is used with OLE servers (Visual Basic, Professional Edition only).

Compatible OLE Server

The name of the .EXE file for the current project, if the .EXE file is an OLE server (OLE server is selected under StartMode).  When an executable file is entered in the Compatible OLE server field, Visual Basic checks to see if any changes you make to a project with a public class module won't introduce potential incompatibilities or break code in the controlling applications that used previous versions of the OLE server (Visual Basic, Professional Edition only).

Application Description

A brief description of the application when the application's object library is displayed in the References and Object Browser dialog boxes.


See Also

Object Browser

Options Command (Tools Menu)


Advanced Options Tab

See Also

Use the Advanced tab of the Options dialog box to specify settings for various advanced features as they apply to the current Visual Basic project.

To open the Advanced tab of the Options dialog box, choose Options from the Tools menu, then click the Advanced tab.

To close the Options dialog box, double-click the Control-menu box or press the ESC key.  To accept the settings in the Options dialog box, choose OK.

Tab Options

Error Trapping

Determines how errors are handled in the Visual Basic development environment.  Setting this option affects all instances of Visual Basic started after you change the setting.

Break on All Errors [image] Any error causes the project to enter break mode, whether or not an error handler is active and whether or not the code is in a class module.

Break In Class Module [image] Any unhandled error produced in a class module causes the project to enter break mode at the line of code in the class module which produced the error.

When you are debugging an OLE server project by running an OLE client test program in another project, set this option in the OLE server project to cause the OLE server to break on errors in its class modules, instead of always returning the error to the client test program.

Break on Unhandled Errors [image] If an error handler is active, the error is trapped without entering break mode.  If there is no active error handler, the error causes the project to enter break mode.  An unhandled error in a class module, however, causes the project to enter break mode on the line of code that invoked the offending procedure of the class.

Use OLE DLL Restrictions

Runs an OLE DLL project within the Visual Basic development environment using the same restrictions that govern the behavior of the OLE DLL when it runs in-processwith another application.

Your OLE DLL project cannot run in-process when you are debugging it in the development environment.  Debugging must be done out of process, using a client test program running in another instance of Visual Basic.  Selecting this option makes the debugging environment more like running in-process, by applying the same restrictions that govern the behavior of a Visual Basic OLE DLL when it runs in-process with another application.

Upgrade Custom Controls

Determines whether Visual Basic should upgrade all the VBX custom controls in a project when that project loads; only valid if there is a replacement OLE custom control registered in VB.INI.

Background Project Load

Determines whether code is loaded in the background, returning control to the developer more quickly

Command-Line Arguments

The command-line arguments that Visual Basic sends to an application (sent only when you choose Start from the Run menu).

Conditional Compilation Arguments

Lists the constant declarations used for conditional compilation.

Compile on Demand

Determines whether a project is fully compiled before it starts, or whether code is compiled as needed, allowing the application to start sooner.

Background Compile

Determines whether idle time is used during run time to finish compiling the project in the background.  Background Compile can improve run time execution speed. This feature is not available unless Compile on Demand is also selected.


See Also

Options Command (Tools Menu)


Form Window

See Also

Use a form to create the windows and dialog boxes in your application.  You draw and view controls on a form.

To create a new form, choose Form from the Insert 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 for that form.

To add an existing form that isn't currently in your project, choose the Add File command from the File menu.

While you are designing a form:

Each form window has a Control-menu box, Minimize and Maximize buttons, and a title bar.  You can move and resize a form.  The form you design will have the same features at design time and at run time unless you specify otherwise in the form's properties.

Use the buttons in the Toolbox to draw controls on the form.


See Also

Form Command (View Menu)

Project Window

Toolbox


Menu Bar

Click a menu or button on the graphic above for more information.

The Visual Basic menu bar includes a title bar, a Minimize button, a Maximize button, a Control-menu box, 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 ALT+the access key.

To choose a command after 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 located on the menu next to the command name.

Commands followed by an ellipsis (...) display a dialog box which provides or requires more information before the command is executed.

Closing the menu bar also closes Visual Basic.


Menu Editor

See Also

Use the Menu Editor to create custom menus for your application and to define their properties.

To open the Menu Editor, select a form and then choose Menu Editor from the Tools menu, or use the toolbar shortcut:

To close the Menu Editor, double-click the Control-menu box.  To accept changes in the Menu Editor, choose OK.

The Menu Editor consists of:

Caption.  A text box in which you enter the menu or command name that appears 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 access key.  If you need an ampersand in the menu, put two consecutive ampersands in the caption.

Name.  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 doesn't appear in a menu.

Index.  A text box in which you assign a numeric value that determines the control's position within a control array.  This position isn't related to the screen position.

Shortcut.  A drop-down list box from which you can select a shortcut key.

HelpContextID.  A text box in which 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.

NegotiatePosition.  A drop-down list box from which you can select the menu's NegotiatePosition property.  This property determines whether and how the menu appears in a container form.

Checked.  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.

Enabled.  A check box you select if you want the menu item to respond to events, or clear if you want the item to be unavailable and appear dimmed.

Visible.  A check box you select if you want the menu item to appear on the menu.

WindowList.  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 set of outlining buttons that enable you to move menu items to a higher or lower level:

   Use these buttons 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 buttons 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 Editor also has the following buttons:

Button	Description

Next	Moves selection to the next line.

Insert	Inserts a line in the list box above the currently selected line.

Delete	Deletes the currently selected line.

OK	Closes the Menu Editor and applies all changes to the last form you selected.  The menu is available at design time, but selecting a menu at  design time opens the Code window for that menu's Click event rather than executing any event code.

Cancel	Closes the Menu Editor and cancels all changes.


See Also

HelpFile Property

Menu Editor (Tools Menu)

NegotiatePosition Property


Object Browser

See Also

The Object Browser displays the classes, properties, and methods available from object libraries and the modules and procedures in your project.  You can use it to find and use objects you create, as well as objects from other applications.

To open the Object Browser, choose Object Browser from the View menu, press F2, or use the toolbar shortcut:

To close the Object Browser, double-click the Control-menu box, or choose the Paste button to paste the current selection into an active Code window.

Dialog Box Options

Libraries/Projects

Displays the libraries available to your project; use the References dialog box to add an object library to the Object Browser.  You can select from available object libraries, including your own Visual Basic projects, to view the classes, modules, procedures, methods, and properties you can use in code.

Classes/Modules

If you select your own Visual Basic project in the Libraries/Projects box, this box displays modules from your project, including any classes you defined in the current project.  If you select an object library in the Libraries/Projects box, it displays the classes available in that library.

In addition, you can select Constants in the Classes/Modules box to view the intrinsic constants for the Visual Basic (VB) and Visual Basic for applications (VBA) object libraries.  For example, if you select VB (Visual Basic ) in the Libraries/Projects box and then select Constants in the Classes/Modules box, you can select one of the constants listed in the Methods/Properties box (for instance, vbAlignLeft), and then paste it into your code.

If you set a reference to the Microsoft Data Access (DAO) 2.5 object library, Microsoft Excel, or any other application that supplies an object library, you can view the intrinsic constants provided by those applications.

Methods/Properties

If you select your own project in the Libraries/Projects box, this box displays procedures, properties, and methods you've defined.  If you select an object library in the Libraries/Projects box, it displays methods and properties for the class that is selected in the Classes/Modules box.

"?" button

Displays the online Help topic for the item selected in the Classes/Modules or Methods/Properties box.

A description and/or a procedure template for the selected item is displayed next to this button.

Show

Displays the selected procedure in the Code window.

Paste

Pastes a template of Visual Basic code for a method or property into a procedure.  First place the insertion point where you want the code fragment to appear in the Code window.  Then select the method or property in the Object Browser.  Click the Paste button to copy the procedure template for the selected item into the Code window.

Options

Displays the Member Options dialog box, which you can use to add Help information or comments about modules, procedures, classes, properties, and methods that you define in your project.  This lets you scroll through a list to see descriptions and comments for the procedures in your forms and modules.


See Also

Member Options Dialog Box

Object Browser Command (View Menu)

References Dialog Box


Project Window

See Also

The Project window displays a list of all the project's form modules, class modules, and standard modules, as well as a single resource file (if one is used in the project).

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:

Note   A check mark to the left of a filename in the Project window indicates that the file is checked out of a version control project, and currently has read/write status.  The check mark is only displayed if you are connected to a version control program, such as Microsoft SourceSafe, which is included with the Enterprise Edition of Visual Basic.

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, standard, or class module by selecting the 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.

You can remove a file from a project by selecting the file in the Project window, and then from the File menu, choose Remove File. Note that this may also remove the file from your source code control program, such as Microsoft SourceSafe, if you are using one.


See Also

Code Window

Connecting to the SourceSafe Add-In

Form Window

Project Command (View Menu)

Remove File Command (File Menu)


Properties Window

See Also

The Properties window contains the list of design-time properties for a selected form, control, class, module, or menu.  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 View menu, press F4, or use the toolbar shortcut:

To close the Properties window, double-click the Control-menu box.

To return to the previously selected window, press ALT+F6.

To switch to the current form, press SHIFT+F7.

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 Properties list.  This two-column list shows all properties that can be changed at design time, as well as their current settings.  To change a property's setting, select the property name and type or select the new setting.  For properties that have predefined settings, you can display the list of settings by clicking the down arrow at the right of the settings box, or you can cycle through the list of available settings by double-clicking the property name in the left column.


See Also

Properties Command (View Menu)


Toolbar

See Also

Click a menu or button on the graphic above for more information.

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.  During compilation, this region displays a status bar that visually indicates how the compilation is progressing; the toolbar must be visible for the status bar to be displayed.

Click a toolbar button once to carry out the action represented by that button.  You can select the Show ToolTips option in the Environment tab of the Options dialog box if you want to display ToolTips for the toolbar buttons.  To toggle the toolbar display, choose Toolbar from the View menu.

The toolbar buttons are:

Creates a new form.

Creates a new standard module.

Opens an existing project.

Saves the current project.

Locks and unlocks the controls on the active form.

Displays the Menu Editor.

Displays the Properties window.

Displays the Object Browser.

Displays the Project window.

Starts an application from design time.

Pauses execution of a program while it's running.

Stops execution of an application and returns to design time.

Toggles the breakpoint on the current line.

Displays the value of the current selection in the Code window.

Displays the structure of active calls.

Traces through each line of code and steps into procedures.

Executes code one procedure or statement at a time in the Code window.


See Also

Environment Options Tab

Toolbar Command (View Menu)


Toolbox

See Also

The Toolbox contains the tools you use to draw controls on your forms.  It displays all the standard Visual Basic controls plus any custom controls and insertable objects you have added to your project with the Custom Controls dialog box.  You can display ToolTips for the Toolbox buttons by selecting the Show ToolTips option in the Environment tab of the Options dialog box.

To open the Toolbox, choose Toolbox from the View menu.

To close the Toolbox, double-click the Control-menu box.

There are 26 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.

When you select the pointer, you can only resize or move a control.

When you select any other tool, you can use it only to draw new controls.

After you draw a control, the pointer is automatically reselected.

 PictureBox.  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.

 TextBox.  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, and then draw controls inside the frame.

 CommandButton.  Use to create a button the user can choose to carry out a command.

 CheckBox.  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.

 OptionButton.  Use in a group of option buttons to display multiple choices from which the user can choose only one.

 ComboBox.  Use to draw a combination list box and test box.  The user can either choose an item from the list or enter a value in the text box.

 ListBox.  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.

 HScrollBar (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.

 VScrollBar (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 generate timer events at set intervals.  This control is invisible at run time.

 DriveListBox.  Use to display valid disk drives.

 DirListBox (directory list box).  Use to display directories and paths.

 FileListBox.  Use to display a list of files.

 Shape.  Use to draw a variety of shapes on your form at design time.  You can choose a rectangle, rounded rectangle, 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 PictureBox.

 Data.  Use to provide access to data in databases through bound controls on your form.

 OLE Container.  Use to link and embed objects from other applications in your Visual Basic application.

 CommonDialog.  Use to create dialog boxes for operations such as opening, saving, and printing files, or selecting colors and fonts.  CommonDialog is a custom control.

 Grid.  Use to display a series of rows and columns and to manipulate the data in its cells.  Grid is a custom control.

 DBList (data-bound 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.  DBList is a custom control and has increased data access capabilities that the standard ListBox doesn't have.

 DBCombo (data-bound 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. DBCombo is a custom control and has increased data-access capabilities that the standard ComboBox doesn't have.

 DBGrid (data-bound grid).  Use to display a series of rows and columns and to manipulate the data in its cells. DBGrid is a custom control and has increased data access capabilities that the standard Grid doesn't have.


See Also

Controls

Custom Controls Dialog Box

Environment Options Tab

Toolbox Command (View Menu)


Add Watch Dialog Box

See Also

The Add Watch dialog box is used to enter a watch expression.  The expression can be a variable, a property, a function call, or any other valid Basic expression.  Watch expressions are updated in the Watch pane of the Debug window each time you enter break mode or after execution of each statement in the Immediate pane.

Important   When selecting a context for a watch expression, use the narrowest scope that fits your needs.  Selecting all procedures or all modules could slow down module execution considerably, since the expression is evaluated after execution of each statement.  Selecting a specific procedure for a context affects execution only while the procedure is in the list of active procedure calls, which you can see by pressing the button to the right of the Procedure box in the Debug window, or by choosing the Calls command on the Tools menu.

To open the Add Watch dialog box, choose Add Watch from the Tools menu.

Type an expression in the Expression box.  If you select an expression first, it is automatically displayed in the Expression box.

To add the expression in the Expression box, choose OK or press ENTER.

To close the Add Watch dialog without adding the expression, choose Cancel or double-click the Control-menu box.

Dialog Box Options

Expression box

Displays the selected expression by default.  The expression is a variable, a property, a function call, or any other valid expression.  You may enter a different expression to evaluate.

Context

Sets the scope of the variables watched in the expression.

Procedure [image] Displays the procedure name where the selected term resides (default).  Defines the procedure(s) in which the expression is evaluated.  You may select all procedures or a specific procedure context in which to evaluate the variable.

Module [image] Displays the module name where the selected term resides (default).  You may select all modules or a specific module context in which to evaluate the variable.

Project [image] Displays the name of the current project.  Expressions can't be evaluated in a context outside of the current project.

Watch Type

Determines how Visual Basic responds to the watch expression.

Watch Expression [image] Displays the watch expression and its value in the Watch pane of the Debug window.  When you enter break mode, the value of the watch expression is automatically updated.

Break When Expression Is True [image] Execution automatically enters break mode when the expression evaluates to true or is any nonzero value (not valid for string expressions).

Break When Expression Has Changed [image] Execution automatically enters break mode when the value of expression changes within the specified context.


See Also

Add Watch Command (Tools Menu)

Adding Watch Expressions

Calls Command (Tools Menu)

Debug Window

Edit Watch Dialog Box

Instant Watch Dialog Box

Setting and Clearing Breakpoints

Using the Immediate Pane


Calls Dialog Box

See Also

During break mode, the Calls dialog box displays a list of currently active procedure calls.  When executing code in a procedure, that procedure is added to a list of active procedure calls.  Each time a procedure calls another procedure, it is added to the list, and so on.  Called procedures are removed from the list when execution returns to the calling procedure.  Procedures called from the Immediate pane are also added to the calls list.

To display the Calls dialog box, press the button to the right of the Procedure box in the Debug window, choose Calls from the Tools menu, or use the toolbar shortcut: .

To display a procedure, select the procedure name in the list and choose Show.

To close the dialog box, choose Close or double-click the Control-menu box.


See Also

Calls Command (Tools Menu)

Debug Window


Edit Watch Dialog Box

See Also

The Edit Watch dialog box is used to delete or edit the context or type of a watch expression.

Important   When selecting a context for a watch expression, use the narrowest scope that fits your needs.  Selecting all procedures or all modules could slow down module execution considerably, since the expression is evaluated after execution of each statement.  Selecting a specific procedure for a context affects execution only while the procedure is in the list of active procedure calls, which you can see by clicking the button to the right of the Procedure box in the Debug window.

To open the Edit Watch dialog box, choose Edit Watch from the Tools menu or double-click an existing expression in the Watch pane of the Debug window.  The selected expression appears in the dialog box (default).

To delete the expression, choose Delete.

To save any changes to expression, choose OK.

To close the Edit Watch dialog box without adding or changing the expression, choose Cancel or double-click the Control-menu box.

Dialog Box Options

Expression box

Displays the selected expression by default.  The expression is a variable, a property, a function call, or any other valid expression.  You may enter a different expression to evaluate.

Context

Sets the scope of the variables watched in the expression.

Procedure [image] Displays the procedure name where the selected term resides (default).  Defines the procedure(s) in which the expression is evaluated.  You may select all procedures or a specific procedure context in which to evaluate the variable.

Module [image] Displays the module name where the selected term resides (default).  You may select all modules or a specific module context in which to evaluate the variable.

Project [image] Displays the name of the current project.  Expressions can't be evaluated in a context outside of the current project.

Watch Type

Determines how Visual Basic responds to the watch expression.

Watch Expression [image] Displays the watch expression and its value in the Watch pane of the Debug window.  When you enter break mode, the value of the watch expression is automatically updated.

Break When Expression Is True [image] Execution automatically enters break mode when the expression evaluates to true or is any nonzero value (not valid for string expressions).

Break When Expression Has Changed [image] Execution automatically enters break mode when the value of expression changes within the specified context.

Delete

Deletes the watch expression.


See Also

Add Watch Dialog Box

Adding Watch Expressions

Debug Window

Deleting Watch Expressions

Edit Watch Command (Tools Menu)

Editing Watch Expressions

Instant Watch Dialog Box

Setting and Clearing Breakpoints

Using the Immediate Pane


Instant Watch Dialog Box

See Also

The Instant Watch dialog box displays the current value of a selected expression.  This functionality is useful when debugging your code if you want to see the current value of a variable, property, or other expression.

To display the Instant Watch dialog box, select an expression and choose Instant Watch from the Tools menu, press SHIFT+F9, or use the toolbar shortcut: .

To add the expression to the Watch pane, choose the Add button in the Calls dialog box.

To close the Instant Watch dialog box, choose Cancel, or double-click the Control-menu box.

Dialog Box Options

Current Context

The names of the project, module, and procedure where the watch expression resides.

Expression

The selected expression.

Value

The value of the selected expression.  The current value isn't displayed if the expression context isn't a within a procedure listed in the Calls dialog box.

Add

Adds the expression to the Watch pane.


See Also

Add Watch Dialog Box

Adding Watch Expressions

Calls Dialog Box

Debug Window

Deleting Watch Expressions

Edit Watch Dialog Box

Editing Watch Expressions

Instant Watch Command (Tools Menu)

Setting and Clearing Breakpoints

Using the Immediate Pane


Scroll Bar

Scroll bars are graphical devices used to scroll parts of a window vertically and horizontally with a mouse. Scroll bars are located at the right and bottom edges of a window.

To scroll within a window

Do one of the following:

To scroll:	Do this:

Up one line	Click the up scroll arrow.

Up one window	Click above the scroll box in the vertical scroll bar.

To an approximate location	Drag the scroll box.

Down one line	Click the down scroll arrow.

Down one window	Click below the scroll box in the vertical scroll bar.

To the left	Click the left scroll arrow.

Left one window	Click left of the scroll box in the horizontal scroll bar.

To the right	Click the right scroll arrow.

Right one window	Click right of the scroll box in the horizontal scroll bar.

A scroll bar includes:

scroll arrow

A button with an arrow that appears at each end of the scroll bar.  The arrow indicates the direction the window contents move when scrolled.  For example, an up scroll arrow moves towards the top, a down scroll arrow moves towards the bottom, and so on.

scroll box

A square within the scroll bar that indicates your relative position within the window.

To move quickly through a window, drag the scroll box along the scroll bar.


Insert Procedure Dialog Box

See Also

Use to insert a new Sub, Function, or Property procedure.  The Insert Procedure dialog box also allows you to set the scope to public or private, and make all local variables in the procedure static.

To open the Insert Procedure dialog box, choose Procedure from the Insert menu.

To close the Insert Procedure dialog box, double-click the Control-menu box, or choose Cancel.

Dialog Box Options

Name

The name for the new procedure.

Type

The type of procedure to create.  Select:

Sub [image] To create a new Sub procedure.

Function [image] To create a new Function procedure.

Property [image] To create a new Property procedure.

Scope

Sets the procedure's scope to either public or private.

All Local Variables as Statics

Adds the Static keyword to the procedure definition.

OK

Inserts the procedure template in the Code window.

Cancel

Closes the dialog box without inserting a new procedure.


See Also

Code Window

Procedure Command (Insert Menu)


EXE Options Dialog Box

See Also

Use this dialog box to set attributes for the executable file you make for your project.

To open the EXE Options dialog box, from the File menu, choose Make EXE File, and then choose the Options button in the Make EXE File dialog box.

To close the EXE Options dialog box, choose OK to approve any changes to the settings, or choose Cancel to close the dialog box without making any changes.

Dialog Box Options

Version Number

Major [image] The major release number of the project; 0 [image] 9999.

Minor [image] The minor release number of the project; 0 [image] 9999.

Revision [image] The revision version number of the project; 0 [image] 9999.

Auto Increment [image] If selected, automatically increases the Revision number by one each time you run the Make EXE File command for this project.

Application

Title [image] The name of the application.

Icon [image] The icon for the application.

Version Information

Type [image] The type of information for which you can set a value.  You can enter information for your company name, file description, legal copyright, legal trademarks, and product name.

Value [image] The value for the type of information selected in the Type box.

Remote Server Support Files (Enterprise Edition)

When checked, Visual Basic creates a file with a .VBR filename extension and the same filename as the .EXE file.  This .VBR file contains information needed by the Windows registry to run an OLE Server on a remote computer.  This option is only available in the Enterprise edition of Visual Basic.


See Also

Make EXE File Command (File Menu)


Member Options Dialog Box

See Also

Use the Member Options dialog box to add Help information or comments about modules, procedures, classes, properties, and methods that you define in your project.  This lets you scroll through a list to see descriptions and comments for the procedures in your forms and modules.

To open the Member Options dialog box, from the View menu, choose Object Browser, select a valid item in the Classes/Modules or Methods/Properties box, and then choose the Options button.

To close the Member Options dialog box, double-click the Control-menu box, or choose Cancel.

Dialog Box Options

Member Name

Displays the name of the item selected in the Classes/Modules or Methods/Properties box.

Description

Enter a description for the member name.  This will be displayed next to the "?" button when the member is selected in the Object Browser.

Help File

Displays the Help file associated with the item listed in the Member Name box.  This is set in the Help File field in the Project tab of the Options dialog box.

Help Context ID

Assign a unique numeric value for the context ID.  This value is used to find the appropriate Help topic in the Help File box.


See Also

Object Browser Command (View Menu)

Object Browser

Project Options Tab


Custom Control Upgrade Dialog Box

See Also

Once you select the Upgrade Custom Controls option in the Advanced tab of the Options dialog box, when you load a project containing VBX custom controls, Visual Basic determines if any appropriate OLE replacement controls are available on your system.  If there are, the Custom Control Upgrade dialog box prompts you to confirm that you want to replace the VBX custom controls.

Choosing Yes replaces the VBX custom controls with OLE custom controls.

If you choose No, Visual Basic won't replace any controls and loads the project with the existing VBX custom controls.

Note   Replacement compatibility is determined by the OLE control vendor.  Before replacing a VBX custom control with an OLE custom control, be sure to check the OLE control vendor's documentation to see if you need to modify event procedures or other code associated with your project's use of the replacement controls.


See Also

Custom Controls Dialog Box

Advanced Options Tab


Multiple Procedure Instances Dialog Box

This dialog box appears when you choose Procedure Definition from the View menu or press SHIFT+F2 and Visual Basic finds more than one procedure in the project with the same procedure name.

Select the procedure whose definition you want to view in this dialog box and then choose OK.


OLE DLL Options Dialog Box

See Also

Use this dialog box to set attributes for the dynamic-link library (DLL) you make for your project.

To open the OLE DLL Options dialog box, from the File menu, choose Make DLL File, and then choose the Options button in the Make OLE DLL File dialog box.

To close the OLE DLL Options dialog box, choose OK to approve any changes to the settings, or choose Cancel to close the dialog box without making any changes.

Dialog Box Options

Version Number

Major [image] The major release number of the project; 0 [image] 9999.

Minor [image] The minor release number of the project; 0 [image] 9999.

Revision [image] The revision version number of the project; 0 [image] 9999.

Auto Increment [image] If selected, automatically increases the Revision number by one each time you run the Make OLE DLL File command for this project.

Application

Title [image] The name of the application.

Icon [image] The icon for the application.

Version Information

Type [image] The type of information for which you can set a value.  You can enter information for your company name, file description, legal copyright, legal trademarks, and product name.

Value [image] The value for the type of information selected in the Type box.

DLL Base Address

Preferred address in memory for the OLE DLL.  If the OLE DLL is unable to load at the preferred address, it automatically finds a suitable address; however, the OLE DLL may take longer to load into memory in this case.  By specifying a base address, you may improve the performance of the OLE DLL by anticipating and avoiding conflicts with other OLE DLLs.

Remote Server Support Files (Enterprise Edition)

When checked, Visual Basic creates a file with a .VBR filename extension and the same filename as the .DLL file.  This .VBR file contains information needed by the Windows registry to run an OLE Server on a remote computer.  This option is only available in the Enterprise edition of Visual Basic.


See Also

Make OLE DLL File Command (File Menu)


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 features, products, and services, which make Microsoft Windows, Microsoft Windows NT, and Microsoft Visual Basic more accessible for people with disabilities:

Microsoft services for people who are deaf or hard-of-hearing.

Access Packs for Microsoft Windows or Microsoft Windows NT, a software utility that makes using Windows and Windows NT easier for people with motion or hearing disabilities.

Keyboard layouts for single-handed users.

Microsoft documentation in alternative formats.

Third-party utilities to enhance accessibility.

Customizing Windows or Windows NT.

Getting more information about products and services for people with disabilities.

Note   The information in this section applies only to users who purchased Windows or Windows NT in the United States.  If you purchased Windows or Windows NT outside the United States, your Windows package contains a subsidiary information card listing Microsoft Support Services 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.


Microsoft Services for People Who Are Deaf or Hard-of-Hearing

Through a text telephone (TT/TDD) service, Microsoft provides people who are deaf or hard-of-hearing with complete access to Microsoft product and customer services.

You can contact Microsoft Sales Information Center on a text telephone by dialing (800) 892-5234 between 6:30 a.m. and 5:30 p.m. Pacific time.


Access Packs for Microsoft Windows and Microsoft Windows NT

Microsoft distributes Access Packs for Microsoft Windows and Microsoft Windows NT, which provide people with motion or hearing disabilities better access to computers running Windows or Windows NT. (If you are running Microsoft Windows 95, these same Access Pack features are already built in.) Microsoft Windows and Microsoft Windows NT contain features that:

Allow single-finger typing of SHIFT, CTRL, and ALT keys 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 by using the keyboard.

Enable you to control the computer keyboard and mouse by using an alternate input device.

Provide a visual cue when the computer beeps or makes sounds.

Access Pack for Microsoft Windows is included on the Microsoft Windows Driver Library in the file ACCP.EXE.  Access Pack for Microsoft Windows NT is included in the Microsoft Application Note WNO789.  If you have a modem, you can download ACCP.EXE or WNO789.EXE, which are self-extracting archive files from the following network services:

CompuServe

GEnie

Microsoft OnLine

Microsoft Download Service (MSDL), which you can reach by calling (206) 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, 9600 or 14400

Parity	None

Data bits	8

Stop bits	1

Various user-group bulletin boards (such as the bulletin board services on the Association of PC User Groups network)

In /SOFTLIB/MSLFILES on the Internet servers FTP.MICROSOFT.COM and WWW.MICROSOFT.COM

People within the United States who do not have a modem can order the Access Packs by calling Microsoft Sales Information Center at (800) 426-9400 (voice) or (800) 892-5234 (text telephone).  In Canada, you can call (905) 568-3503 (voice) or (905) 568-9641 (text tehone).


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 with their left hand only, and one for people who type with their right hand only.  The left-handed or right-handed 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 and Microsoft Windows NT already support the two-handed Dvorak layout, which can be useful for coping with or avoiding types of repetitive-motion injuries associated with typing.  To get this layout, use the Windows Control Panel; consult your online documentation for detailed instructions.  The two layouts for people who type with one hand are distributed as Microsoft Application Note GA0650.  It is also contained in file GA0650.EXE on most network services and on the Microsoft Download Service.  For instructions on oining this application note see Access Packs for Microsoft Windows and Microsoft Windows NT.


Microsoft Documentation in Alternative Formats

People who have difficulty reading or handling printed documentation may obtain many Microsoft publications from Recording for the Blind, Inc.  Recording for the Blind distributes these documents to registered eligible members of their distribution service either on audio cassettes or on floppy disks.  The Recording for the Blind 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 or phone numbers for information on eligibility and availability of Microsoft product documentation and books from Microsoft Press:

Recording for the Blind, Inc.
20 Roszel Road
Princeton, NJ  08540

Phone: (609) 452-0606
Fax: (609) 987-8116

Visual Basic version 4.0 Professional edition and Enterprise edition documents are also available on a CD that is included with the package.


Third-Party Utilities to Enhance Accessibility

A wide variety of third-party hardware and software products are available to make personal computers easier to use for people with disabilities.  Among the different types of products available for the MS-DOS, Microsoft Windows, and Microsoft Windows NT operating systems are:

Programs that enlarge or alter the color of information on the screen for people with visual impairments.

Programs that describe information on the screen in braille or synthesized speech for people who are blind or have difficulty reading.

Hardware and software utilities that modify the behavior of the mouse and keyboard.

Programs that enable users to type using a mouse or their voice.

Word or phrase prediction software that allows one to type more quickly and with fewer keystrokes.

Alternate input devices, such as single switch or puff-and-sip devices, for those who cannot use a mouse or a keyboard.

For more information on obtaining third-party utilities, see Getting More Information.  For more information about customizing Windows and Windows NT for people with low vision, see Customizing Windows or Windows NT.


Customizing Windows or Windows NT

There are many ways you can adjust the appearance and behavior of Windows or Windows NT 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.

See the appropriate application note for information related to customizing your operating system for people with disabilities.  For information on obtaining application notes, see Access Packs for Microsoft Windows and Microsoft Windows NT.

Operating system	Application note number

Microsoft Windows 3.0	WW0786.TXT

Microsoft Windows 3.1	WG0787.TXT

Microsoft Windows for Workgroups 3.1	WG0788.TXT

Microsoft Windows NT 3.1 and 3.5	WN0789.EXE

Microsoft Windows 95	WN1062


Getting More Information

For more information on Microsoft products and services for people with disabilities, contact:

Microsoft Sales Information Center
One Microsoft Way
Redmond, WA 98052-6393

Voice telephone: (800) 426-9400
Text telephone: (800) 892-5234
Fax: (206) 635-6100

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 approximately 2,000 products.  The compact disc, titled Co-Net CD, provides a database of more than 18,000 products and other information for people with disabilities.  It is issued twice a year.  To obtain these directories, contact:

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-8848

For general information and recommendations on how computers can help specific people, you should consult a trained evaluator who can best match your needs with the available solutions.  An assistive technology program in your area will provide referrals to programs and services that are available to you.  To locate the assistive technology program nearest you, you can contact:

National Information System
Center for Developmental Disabilities
Benson Building
University of South Carolina
Columbia, SC 29208

Voice/text telephone: (803) 777-4435
Fax: (803) 777-6058


Precision lost converting Variant (Error 12)

Visual Basic changed the internal representation it was using to store a value and, in the process, the value lost some of its precision.  This error has the following cause and solution:

A fraction may have been stored as a Variant data type and then you used a conversion function to change it to an Integer or Long data type.

To maintain numeric precision and speed up your code, store a number as a specific Numeric data type instead of as a Variant.


No timer available (Error 260)

The number of Timer controls in a project and the amount of memory each requires are limited.  This error has the following causes and solutions:

There are too many Timer controls active.  The maximum number varies from environment to environment.

Remove one or more Timer controls from the project.

There isn't enough memory to load another 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.  This error has the following causes and solutions:

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 isn't 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.  This error has the following causes and solutions:

Too many forms have their LinkMode property set to something other than 0 (None).

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.  This error has the following causes and solutions:

The application specified in LinkTopic isn't running.

Ensure that the specified application is running.

The application is running, but doesn't recognize the topic of the link.

Ensure that the specified application actually has a topic with the name specified in LinkTopic.


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 error has the following cause and solution:

Several instances of the same application are running and you are attempting to initiate a DDE conversation on a topic more than one of them recognize.

Ensure that the combination of application and topic is unique by closing all instances except one of the running application.


DDE channel locked (Error 284)

You have attempted to initiate a new DDE conversation or perform a DDE method on a DDE link whose channel can't be opened.  This error has the following cause and solution:

Another application is running that has the same DDE link open.

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.  This error has the following causes and solutions:

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 isn't 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 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.  This error has the following causes and solutions:

The other application isn't 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 Escape key during DDE operation (Error 287)

You pressed the ESC key while waiting for a DDE operation to be completed.  This error has the following cause and solution:

The other application in the DDE conversation is taking too long to respond.

Try setting the LinkTimeout property to a lower value.


Destination is busy (Error 288)

The other application in the DDE conversation can't perform a DDE operation.  This error has the following cause and solution:

The other application is busy responding to other Windows events.

Try calling the DoEvents function and attempt the DDE operation again.


Data not provided in DDE operation (Error 289)

Visual Basic encountered an unexpected error while attempting to perform a DDE operation.  This error has the following cause and solution:

The other application informed Visual Basic it was supplying data in a DDE conversation but did not provide it when requested.

Ensure that the other application is performing DDE correctly and actually has the data specified.


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.  This error has the following causes and solutions:

The application is supplying data in a format that Visual Basic doesn't recognize.

Try initiating the conversation with a different topic.

The application is supplying text data to a PictureBox or picture data to a TextBox.

Try initiating the conversation with a different control.


Foreign application quit (Error 291)

A DDE operation can't take place unless the other application is running.  This error has the following cause and solution:

  	The other application in a DDE conversation quit unexpectedly.

Determine why the other application quit and then restart it.


DDE conversation closed or changed (Error 292)

Visual Basic encountered an unexpected error while attempting to perform a DDE operation.  This error has the following cause and solution:

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 isn't involved in a valid DDE conversation.  This error has the following causes and solutions:

Changing the LinkTopic property terminates an existing DDE conversation but doesn't automatically establish a new conversation.

After changing the LinkTopic property for a control, you must set the LinkMode property of the form 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 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 an invalid format.  This error has the following cause and solution:

The application passed data in the vbCFLink Clipboard format but it isn't valid link data.

Fix the data in the other application so that it conforms to the vbCFLink Clipboard format.


Message queue filled; DDE message lost (Error 295)

Visual Basic can't keep up with the number of DDE operations attempted.  This error has the following causes and solutions:

Too many DDE conversations are running.

Try terminating one or more 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.  This error has the following cause and solution:

You are trying to paste a new link while a prior link is still in effect.

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 tried and failed to set the LinkMode property of a control.  This error has the following cause and solution:

You did not specify a LinkTopic property for the control.

First specify a valid LinkTopic property.


System DLL 'dll' could not be loaded (Error 298)

A .DLL file provided by the operating system; for example, DDEML.DLL, VERSION.DLL, or WINSPOOL.DRV couldn't be found.  This error has the following causes and solutions:

The file isn't on the proper path.

Ensure that the DLL is on the Windows System path.

The DLL is corrupted or was deleted.

Reload the DLL.

There isn't enough memory or swap space.

Try to free up some memory by closing other applications.


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

From within Visual Basic, you can't give a file the same name as a character device driver.  This error has the following cause and solution:

You tried to use a filename such as AUX, CON, COM1, COM2, LPT1, LPT2, LPT3, LPT4, or NUL.

Give the file another name.


Invalid file format (Error 321)

A Visual Basic form file is damaged.  This error has the following causes and solutions:

The form has a damaged custom control.

Try replacing the custom control on the form.

The number of properties in the current version of the custom control don't match the number expected.

Try replacing the custom control with an earlier or later version.


Item is not a valid resource file (Error 325)
'Item' is not a valid resource file (Error 325)

A resource file in your project doesn't follow the standard format for a Windows resource file or there is a mismatch between the resource file and the Visual Basic project.  This error has the following causes and solutions:

You tried to use the LoadResString, LoadResPicture, or LoadResData methods on a resource file with an invalid format.

Recreate the resource source and resource files and adhere to the syntax documented in the Windows Software Development Kit.

You tried to make an .EXE file from a project that includes a resource file with an invalid format.

Remove the invalid resource file from the project.

You tried to use the File Add File command to add a 16-bit resource file to a 32-bit project, or vice versa.

Ensure that there is a match in bits between the resource file and the Visual Basic project.


Resource with identifier item not found (Error 326)
Resource with identifier 'item' not found (Error 326)

The resource with the specified ID doesn't exist in the resource file.  This error has the following cause and solution:

You tried to use the LoadResString, LoadResPicture, or LoadResData methods to load a resource whose ID doesn't exist in the resource file associated with this project or .EXE file.

Change the reference to the resource ID to one that does exist or remove the resource file from the project and add a resource file that does contain the specified resource ID.


Could not access system registry (Error 335)

An attempt to read from or write to the system registry failed.  This error has the following cause and solution:

The REG.DAT registration database file may have been deleted or become corrupted.

To restore the registration database:

1	Quit Windows, delete the REG.DAT file, and then restart Windows.

2	Start Registration Info Editor by choosing the Run command in File Manager or Program Manager.  Type REGEDIT.EXE and choose OK.  There will not be any entries in the list of registered file types.

3	From the File menu, choose Merge Registration File.

4	In the File Name list, select the SETUP.REG file, and then choose the OK button.

The SETUP.REG file is located in the SYSTEM subdirectory of your Windows directory.  A message appears, confirming that the information has been successfully registered.  The registration database is updated with the original registration information that came with Windows.

If you have additional applications that have registration information in a .REG file, you can add them to the database by choosing the Merge Registration File command from the File menu.


Object server not correctly registered (Error 336)

The OLE server has not been properly registered in the system registry.  This error has the following cause and solution:

One of the four key entries to the REG.DAT file (ROOT, Typelib, CLSID, Interface) was not made or was made incorrectly; or a key entry was overwritten by a second OLE server simultaneously running with the same project name as the first OLE server.

For information on registering OLE servers, see Chapter 1, "Creating OLE Servers," in the Creating OLE Servers book in Visual Basic Professional Features.


Object server not found (Error 337)

The required EXE or DLL file can't be found.  This error has the following cause and solution:

The OLE server is registered in the registration database (REG.DAT) but the EXE or DLL filename it refers to can't be found.

Ensure that a copy of the OLE server's EXE or DLL file is on the \SYSTEM path.  For more information on OLE servers, see Chapter 1, "Creating OLE Servers," in the Creating OLE Servers book in Visual Basic Professional Features.


Object server did not correctly run (Error 338)

The OLE server's EXE file failed to run correctly.  This error has the following cause and solution:

There may be a problem with the information in the registration database (REG.DAT) or the EXE file may be corrupted.

Remake the OLE server into a new EXE and see if it will run correctly.  For more information on OLE servers, see Chapter 1, "Creating OLE Servers," in the Creating OLE Servers book in Visual Basic Professional Features.


Control array element 'item' doesn't exist (Error 340)
Control array element 'item' does not exist (Error 340)

You used an invalid index value to refer to an element in a control array.  This error has the following cause and solution:

No control with the index value you referred to is part of the existing control array.

Change the Index property setting for one of the existing elements to the value you referred to.  Or use the Load statement to add a control to the array with an index equal to the value and then refer to the index value again.


Invalid control array index (Error 341)

You used an invalid index value to refer to an element in a control array.  This error has the following cause and solution:

The index value you referred to in your code was a negative number.

Change the index value to refer to one of the existing elements of the control array.


Not enough room to allocate control array 'item' (Error 342)

There isn't enough memory to create all the elements of a control array.  This error has the following causes and solutions:

An element in a control array with discontiguous index values for its elements, such as 0, 2, 4, was assigned too large an index value at design time.

Change the Index propertys setting to a smaller value so that Visual Basic doesn't run out of memory.

You used the Load statement to add an element with too large an index value to a control array.

Change the index value in your code to a smaller value.


Object not an array (Error 343)

A control that isn't part of a control array is referred to as if it were.  This error has the following cause and solution:

You tried to refer to an index value for a control that isn't part of an array (for example, Command1(3).Caption and Command1.Text).

Delete the reference to the index value or redefine the control as an element in a control array.


Must specify index for object array (Error 344)

A control that isn't part of a control array is referred to as if it were.  This error has the following causes and solutions:

You referred to an index value for a control that isn't a part of a control array.

Remove the reference to the index value.

You tried to add a control at run time with the Load statement but no control array with that Name property exists.

Create the control you are referring to as a control array at design time.


Reached limit: cannot create any more controls for this form (Error 345)
Reached limit: cannot create any more controls on this form (Error 345)

No more than 255 individual controls are allowed for each form.  This error has the following cause and solution:

At design time you tried to add a control to a form that resulted in a total of 256 individual controls for the form (with the form itself counting as one control).

Delete one or more controls from the form or redefine one or more of your controls as part of a control array.


Object already loaded (Error 360)

The control in the control array has already been loaded.  This error has the following cause and solution:

You tried to add a control to a control array at run time with the Load statement but the index value you referred to already exists.

Change the index reference to a new value or check if your code is executing the same Load statement, with the same index value reference, more than once.


Can't load or unload this object (Error 361)

A Load or Unload statement has referenced an invalid object or control.  This error has the following causes and solutions:

You tried to load or unload an object that isn't a control or form, such as Screen, Printer, or Clipboard.

Delete the erroneous statement from your code.

You tried to load or unload an existing control that isn't part of a control array.  For example, assuming that a TextBox with the Name property Text1 exists, Load Text1 will cause this error.

Delete the erroneous statement from your code or change the reference to a control in a control array.

You tried to unload a Menu control in the Click event of its parent menu.

Unload the Menu control with some other procedure.

You tried to unload the last visible menu item of a Menu control.

Check the setting of the Visible property for the other menu items in the control array before trying to unload a menu item or delete the erroneous statement from your code.


Can't unload controls created at design time (Error 362)

Only a control array element loaded at run time can be unloaded.  This error has the following cause and solution:

You used the Unload statement to refer to a control array element that you created at design time.

Change the index value of the control you want to unload to a control array element that was loaded at run time.  Or you can hide any control by setting its Visible property to False.


Custom control 'item' not found (Error 363)

The form being loaded contains a custom control that isn't part of the current project.  This error has the following causes and solutions:

You may have manually edited the projects .VBP file to add a form containing a custom control that isn't already part of the project.

After the project loads, use the Add File command on the File menu to add the custom control to the project.

You may have manually edited the projects .VBP file to add a form containing a custom control that is an older version than the custom control that is already part of the project.

After the project loads, delete the older version from the form and put the newer version of the control on the form.


Object was unloaded (Error 364)

A form was unloaded from its own Form_Load procedure.  This error has the following cause and solution:

A form with an Unload statement in its Form_Load procedure was implicitly loaded.  For example, the following will implicitly load Form2 if it isn't already loaded: Form2.BackColor = Form1.BackColor.

Remove the Unload statement from the Form_Load procedure.


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.  This error has the following causes and solutions:

There is an Unload statement in the Paint event for the form or for a control on the form that has the Paint event.

Remove the Unload statement from the Paint event.

There is an Unload statement in the Change, Click, or DropDown events of a ComboBox.

Remove the Unload statement from the event.

There is an Unload statement in the Scroll event of an HScrollBar or VScrollBar control.

Remove the Unload statement from the event.

There is an Unload statement in the Resize event of a Data, Form, MDIForm, or PictureBox control.

Remove the Unload statement from the event.

There is an Unload statement in the Resize event of an MDIForm that is trying to unload an MDI child form.

Remove the Unload statement from the event.

There is an Unload statement in the RePosition or Validate event of a Data control.

Remove the Unload statement from the event.

There is an Unload statement in the ObjectMove event of an OLE Container control.

Remove the Unload statement from the event.


No MDI form available to load (Error 366)

There is no MDIForm in your project to load.  This error has the following cause and solution:

You tried to load a form whose MDIChild property is set to True, but at run time there was no MDIForm in your project to load.

Add a MDIForm to your project or change the MDIChild property setting to False.


The file item is out of date. This program requires a newer version. (Error 367)
The file 'item' is out of date. This program requires a newer version (Error 367)

A custom control was found to be out of date.  This error has the following cause and solution:

The number of properties in the current version of the custom control don't match the number expected.

Replace the custom control with a newer version.


Cant load Custom Control DLL: item (Error 368)
Cant load Custom Control DLL: 'item' (Error 368)

Visual Basic could not load the specified custom control dynamic-link library (DLL).  This error has the following causes and solutions:

You attempted to use the Tools Custom Controls command to load a DLL file that isn't a valid Visual Basic custom control DLL.

Only load DLL files with the custom control extensions of .VBX or .OCX.

You opened a project that contained a reference to a custom control DLL.  This DLL file exists but isn't a valid custom control DLL.

The DLL file may have been damaged in some way; try replacing it with an undamaged copy.


Invalid property value (Error 380)

An inappropriate value is assigned to a property.  This error has the following cause and solution:

You tried to set one of the properties of an object or control to a value outside its permissible range.

Change the propertys value to a valid setting.  For example, the MousePointer property must be set to an integer from 0 to 13.


Invalid property array index (Error 381)

An inappropriate property array index value is being used.  This error has the following cause and solution:

You tried to set a property array index to a value outside its permissible range.

Change the index value of the property array to a valid setting.  For example, the index value of the List property for a ListBox must be from 0 to 32,766.


'Item' property cannot be set at run time (Error 382)

The property is read-only at run time.  This error has the following cause and solution:

You tried to set or change a property whose value can only be set at design time.

Remove the reference to the property from your code or change the reference to only return the value of the property at run time.


'Item' property is read-only (Error 383)

The property is read-only at both design time and run time.  This error has the following cause and solution:

You tried to set or change a property whose value can only be read.

Remove the reference to the property from your code or change the reference to only return the value of the property at run time.


A form can't be moved or sized while minimized or maximized (Error 384)
A form cant be moved or sized while minimized or maximized (Error 384)

The Left, Top, Height, and Width properties can't be changed on a minimized or maximized form.  This error has the following causes and solutions:

You tried to use the Move method or change the Left, Top, Height, or Width of the form while it was maximized or minimized.

Check the WindowState property of the form before using the Move method or prevent the user from maximizing or minimizing the form.

The Resize event occurred while the form was maximized or minimized and code in it tried to change the Left, Top, Height, or Width of the form.

Rewrite the code in the Resize event procedure to check the WindowState property of the form and exit the procedure if WindowState is 1 - Minimized or 2 - Maximized.


Must specify index when using property array (Error 385)

You must specify an index value when referring to a property array.  This error has the following cause and solution:

You tried to refer to an element in a property array but omitted the index value specifying the element.

Change your code to include the index value.  For example, List1.List is invalid but List1.List(3) is valid.


'Item' property not available at run time (Error 386)

The propertys setting can't be read at run time.  This error has the following cause and solution:

You tried to return the value of the identified property at run time.

Change your code and remove the reference to the property.


'Item' property can't be set on this control (Error 387)

The propertys setting can't be set at run time or can only be set under certain conditions.  This error has the following causes and solutions:

You tried to change the Auto3D, ControlBox, MinButton, or MaxButton property settings for the form at run time.

You may only read these property values at run time.

You tried to set the Visible property to False for the last remaining 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 cant be set from its parent's menu code.  This error has the following cause and solution:

You tried to set the Visible property of a submenu item from a procedure associated with the submenu items parent Menu.

Place the code reference to the submenu items Visible property in some other controls or objects procedure.


Invalid key (Error 389)

The key that was pressed is invalid.


No Defined Value (Error 390)

No value has been defined for the specified property.


Name not available (Error 391)

A custom control (.VBX) file tried to use the VBGetControlName API against a Visual Basic application in .EXE form.  This error has the following cause and solution:

Visual Basic doesn't embed object names in the executable (.EXE) file.

Consult the author of the .VBX file.


'Item' property cannot be read at run time (Error 393)

The property is only available at design time.  This error has the following cause and solution:

You tried to read a property at run time that is only accessible at design time.

Change your code and remove the reference to the property.


'Item' property is write-only (Error 394)

The property cant be read.  This error has the following cause and solution.

A property can't be read; for example, ctl.property = 3 might be legal, but "Print ctl.property" would generate this error.

Change your code and remove the reference to the property.


Can't use separator bar as menu name (Error 395)

A Menu caption that has submenus can't be changed to a separator bar.  This error has the following causes and solutions:

At either design time or run time, you tried to change the Caption property on a parent or top-level Menu to a separator bar.

Remove the dash character from the Caption text box in the Menu Editor dialog or the Caption property in the Properties window, or change the reference in your code.

At run time, you tried to change the Caption property on a Menu which is checked, disabled, or has a shortcut key to a separator bar.

Change the reference in your code or read the setting of the Checked or Enabled properties before trying to change the Caption property.  You can't read the setting of the Shortcut property at run time.


Item property cannot be set within a page (Error 395)
'Item' property cannot be set within a page (Error 396)

Certain properties of the Printer object can't be changed within a page.  This error has the following cause and solution:

You tried to change the Height, Width, or PaperSize properties of the Printer object before advancing the print job to the next page.

Use the NewPage method before changing the Height, Width, or PaperSize properties.


Cant set Visible property for top level menus while they are merged (Error 397)
Cant set Visible property for top-level menus while they are merged (Error 397)

The Visible property can't be set for a top-level menu while an OLE server's menu is merged with a container form's menu.  This error has the following cause and solution:

You tried to change the Visible property of a top level menu while a Visual Basic container form's menu and a linked or embedded OLE server's menu were sharing the same menu bar.

Test to ensure that menus are not merged before setting Visible for top-level menus.


Form already displayed; can't show modally (Error 400)

You cant use the Show method to display a form as modal that is already visible.  This error has the following cause and solution:

You tried to use Show, with the style argument set to 1 - vbModal, on an already visible form.

Use either the Unload statement or the Hide method on the form before trying to show it as a modal form.


Can't show non-modal form when modal form is displayed (Error 401)

When a modal form is displayed, you cant display another non-modal form.  This error has the following cause and solution:

You tried to use the Show method or set the Visible property to True on a non-modal form when another form is already displayed as modal.

Use either the Unload statement or the Hide method on the modal form before attempting to use the Show method on a non-modal form.


Must close or hide topmost modal form first (Error 402)

The modal form you are trying to close or hide isn't on top of the z-order.  This error has the following cause and solution:

Another modal form is higher in the z-order than the modal form you tried to close or hide.

First use either the Unload statement or the Hide method on any modal form higher in the z-order.  A modal form is a form displayed by the Show method, with the style argument set to 1 - vbModal.


MDI forms cannot be shown modally (Error 403)

You may not set the modal option on an MDIForm.  This error has the following cause and solution:

You tried to use the Show method, with the style argument set to 1 - vbModal, on an MDI parent form.

Remove the style argument reference from your code.

You tried to compile a project with an MDIForm by using the Make OLE File command from the File menu.

MDFforms cannot be put in DLLs.  Remove the MDIForm from the project and then re-compile, or compile the project into an EXE by choosing the Make EXE File command from the File menu.


MDI child forms cannot be shown modally (Error 404)

You may not set the modal option on an MDI child form.  This error has the following cause and solution:

You tried to use the Show method, with the style argument set to 1 - vbModal, on an MDI child form.

Remove the style argument reference from your code.


Permission to use object denied (Error 419)

You don't have the necessary permissions for the specified object.  This error has the following cause and solution:

You don't currently have the authority to access this object.

To change your permission assignments, see your system administrator or the object's creator.


Only one MDI Form allowed (Error 426)

A project can only have one MDIForm.  This error has the following causes and solutions:

You tried to load a file containing an MDIForm into a project that already has an MDIForm in it.

Remove the file containing the loaded MDIForm before loading another.

You tried to load a second instance of an MDIForm created with a Dim or Set statement.

You can only create one instance of an MDIForm in a project.


Invalid object type; Menu control required (Error 427)

The first argument for the PopupMenu method must be a Menu control.  This error has the following cause and solution:

You specified some object other than a Menu control as the menuname argument for the PopupMenu method.

Use the name of a Menu control with at least one submenu as the menuname argument.


Popup menu must have at least one submenu (Error 428)

You have defined a pop-up menu with no submenus.  This error has the following cause and solution:

You specified a Menu control that doesn't have a submenu as the menuname argument for the PopupMenu method.

Use the name of a Menu control with at least one submenu as the menuname argument.


You do not have an appropriate license to use this functionality (Error 429)

You are not a licensed user of the custom control.  This error has the following causes and solutions:

You tried to add a VBX custom control to a project at design time but the associated license file could not be found.

The license file (.LIC extension) may have been deleted or become corrupted.  Reinstall the custom control or contact the custom control vendor.

You tried to place an OCX custom control on a form at design time or tried to add a form to a project with an OCX custom control on it but the associated information in the registration database (REG.DAT) could not be found.

The information in the registration database may have been deleted or become corrupted.  Reinstall the custom control or contact the custom control vendor.


Invalid Clipboard format (Error 460)

The specified Clipboard format is incompatible with the method being executed.  This error has the following causes and solutions:

You tried to use the GetText or SetText method with a Clipboard format other than vbCFText or vbCFLink.

Remove the invalid format and specify one of the two valid formats.

You tried to use the GetData or SetData method with a Clipboard format other than vbCFBitmap, vbCFDIB, or vbCFMetafile.

Remove the invalid format and specify one of the three valid graphics formats.


Specified format doesnt match format of data (Error 461)

The specified Clipboard format is incompatible with the method being executed.  This error has the following causes and solutions:

You tried to use the GetText or SetText method with a Clipboard format other than vbCFText or vbCFLink.

Before using these methods, use the GetFormat method to test if the current contents of the Clipboard matches the specified format.

You tried to use the GetData or SetData method with a Clipboard format other than vbCFBitmap, vbCFDIB, or vbCFMetafile.

Before using these methods, use the GetFormat method to test if the current contents of the Clipboard matches the specified graphics format.


Can't create AutoRedraw image (Error 480)

Visual Basic can't create a persistent bitmap for automatic redraw of the form or picture.  This error has the following cause and solution:

There isn't enough available memory for the AutoRedraw property to be set to True.

Set the AutoRedraw property to False and perform your own redraw in the Paint event procedure or make the PictureBox control or Form object smaller and try the operation again with AutoRedraw set to True.


Invalid picture (Error 481)

An invalid graphics format was assigned to the Picture property.  This error has the following cause and solution:

You tried to assign a graphics format other than a bitmap, icon, or Windows metafile to the Picture property of a form or control.

Ensure that the file you are trying to load into the Picture property is a valid .BMP, .ICO, or .WMF file format.


Printer error (Error 482)

There is some problem that prevents printing.  This error has the following causes and solutions:

You don't have a printer installed from the Windows Control Panel.

Open the Control Panel, double-click the Printers icon, and choose Add to install a printer.

Your printer isn't online.

Physically switch the printer online.

Your printer is jammed or out of paper.

Physically correct the problem.

You tried to print a form to a printer that can accept only text.

Switch to an installed printer that can print graphics.


Printer driver does not support specified property (Error 483)

The printer driver for the printer in use doesn't support this property of the Printer object.  This error has the following cause and solution:

The effect of the properties of the Printer object depends on the driver supplied by the printer manufacturer.  Some property settings may have no effect, or several different property settings may all have the same effect.  Settings outside the accepted range may or may not produce an error.

For more information, see the manufacturer's documentation for the specific driver.


Problem getting printer information from the system. Make sure the printer is set up correctly. (Error 484)

There is some problem that prevents getting printer information from the system.  This error has the following causes and solutions:

You don't have a printer installed from the Windows Control Panel.

Open the Control Panel, double-click the Printers icon, and choose Add to install a printer.

Your printer isn't online.

Physically switch the printer online.

Your printer is jammed or out of paper.

Physically correct the problem.


Invalid picture type (Error 485)

The resource file picture format you tried to load doesn't match the specified property of the object.  This error has the following causes and solutions:

You tried to use the LoadResPicture method to load a bitmap resource as the Icon property of a Form.

Change the property of Form to the Picture property or change the format argument of LoadResPicture to vbResIcon.

You tried to use the LoadResPicture method to load a cursor resource as some property of an object or control other than the MousePointer property.

Change the property reference to MousePointer.


Can't empty Clipboard (Error 520)

The Clipboard was opened but could not be emptied.  This error has the following cause and solution:

Another application is using the Clipboard and will not release it to your application.

Set an error trap for this situation in your code and provide a message box with Retry and Cancel buttons to allow the user to try again after a short pause.


Can't open Clipboard (Error 521)

The Clipboard has already been opened by another application.  This error has the following cause and solution:

Another application is using the Clipboard and will not release it to your application.

Set an error trap for this situation in your code and provide a message box with Retry and Cancel buttons to allow the user to try again after a short pause.


The data binding DLL, 'item', could not be loaded. (Error 523)

Unable to load specified data from DLL.


'item' (Error 524)

The specified error has occurred in the OLE Automation object currently running.


Data Access Error (Error 525)

A Data Access Object error has occurred that was not specifically trapped.


The given bookmark was invalid (Error 527)

You tried to set a bookmark to an invalid string.  This error has the following causes and solutions:

You set the Bookmark property to a string that wasn't saved after reading a records Bookmark property.

Save the string before setting the Bookmark property to it.

You set the Bookmark property to a string that was saved after reading a records Bookmark property, but that record has since been deleted.

Test that the record with the saved Bookmark property still exists before trying to move to it.


Could not lock the database (Error 536)

The database file could not be locked.  This error has the following causes and solutions:

The file SHARE.EXE isn't loaded.

Load SHARE.EXE by adding the following line to your AUTOEXEC.BAT file: SHARE.EXE /L:500.  Then reboot your system and try the operation again.

You tried to lock a table while opening it, but the table can't be locked because it is currently in use.

Wait a moment, and then try the operation again.

You tried to lock 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.


Could not access the desired Column (Error 537)

The column number referred to in the code could not be accessed.  This error has the following cause and solution:

You have attempted to access a column that doesn't exist.

First use the Cols property to set or return the number of columns and then refer only to a column number within that range.


Could not lock the database (Error 541)

The database file could not be locked.  This error has the following causes and solutions:

The file SHARE.EXE isn't loaded.

Load SHARE.EXE by adding the following line to your AUTOEXEC.BAT file: SHARE.EXE /L:500.  Then reboot your system and try the operation again.

You tried to lock a table while opening it, but the table can't be locked because it is currently in use.

Wait a moment, and then try the operation again.

You tried to lock 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 row has been deleted since the update was started (Error 542)

A record cant be updated because it was previously deleted.  This error has the following cause and solution:

Because the LockEdits property for the Recordset object was set to False (optimistic locking) while the record was being edited, another user was able to delete the record before it could be updated.

Set the LockEdits property to True (pessimistic locking).


Item' is a Read-Only file
'Item' is a Read-Only file

You asked to save to a file that is read-only.  Read-only files are shown in the Project window with a red lock in the lower-left corner.  You can't save to read-only 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.  (You can place the cursor on the variable in the Code window and invoke the Instant Watch command.)


An undo error has occurred. Further undo is unavailable.

The Undo/Redo mechanism is unable to perform the operation.  Both undo and redo buffers have been flushed; therefore, old edits can't be undone or redone.  Edits performed after the message are 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 chose OK to close the dialog box.  For a particular form, only one menu can have the Window List check box checked.  To do this, use the Menu Editor.


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

You tried to double-click a control to place it on an MDI form, but the control doesn't support the standard Align property.  A PictureBox is the only standard control that can be placed on an MDI form.  When an MDI child form is maximized within the MDI parent form, it doesn't cover any picture boxes.

An example of good usage: Create a new MDIForm and double-click PictureBox.

An example of bad usage: Create a new MDIForm and double-click TextBox.


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.


New not allowed on this type

Auto-construction isn't 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 Visual Basic Standard Edition, the keyword New can be used only on specific instances of form types (Form1, and so on.).  It can't be used on the general class Form or MDIForm or on any control types.  In the Visual Basic Professional and Enterprise Editions, there are some objects for which New is allowed.


Separator may not be the Window List menu

The window menu has to be a menu item that can support being a pop-up menu (one that can have subitems).  A separator can't have subitems.


Valid range is 1 to 32

You attempted to set the TabStop Width beyond the permitted range.  A number between 1 and 32 (inclusive) is acceptable for this field.


Valid values are whole numbers from 30 to 1185

You attempted to set the Grid Width or Grid Height beyond the permitted range.  A number between 30 and 1185 (inclusive) is acceptable for this field.


Watch expression too long, expression truncated
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, 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 'item' for details

Something unexpected appeared in the ASCII form file.  Visual Basic 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 you can safely ignore the errors (for example, Version number missing or invalid...).  Other times, however, the errors could cause the form not to run as expected (for example, Class MyClass in control  MyControl was not a loaded control class).


String value too long to process; form load aborted

A string embedded in the form being loaded was too long to process.


Version number missing or invalid; Visual Basic 4.0 assumed.

Either the version signature was not found or the specified version isn't recognized.  Make sure that the first line that is not blank or a comment in the ASCII form reads Version 4.00.


Line 'item1': The file 'item2' could not be loaded.

Syntax errors are preventing Visual Basic from parsing and loading, or form name conflicts prevent loading of an ASCII form.  The form won't be loaded and the form name won't be displayed in the Project window.

Make sure that the file causing this error is a valid ASCII form in the correct format and that no conflicts exist among the different forms in the project.  The correct ASCII form format is:

Version 4.00

Begin VB.Form <formname>

Form Properties

Begin VB.<controltype> <controlname>

prop = value

prop = value

[...]

Control Properties

Begin VB.<control type> <control name>

prop = value

[...]

Begin ...

[...]

End

End

End

End


Item' 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 won't be loaded and the form name won't 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 no conflicts exist among the different forms in the project.  The correct ASCII form format is:

Version 4.00

Begin VB.Form <formname>

Form Properties

Begin VB.<controltype> <controlname>

prop = value

prop = value

[...]

Control Properties

Begin VB.<control type> <control name>

prop = value

[...]

Begin ...

[...]

End

End

End

End


Replace operation ended. Changes not completed.

The Replace operation resulted in a statement that will cause a syntax error.  No further replacements were made.


Can't remove control or reference; in use

The custom control or reference that you tried to remove from the list of available references in the Add References dialog box is being used by one of the forms in the project.  First delete the control or reference from the form and then deselect it from the list.


Must have startup form or Sub Main()

No form in the current project is designated as the startup form, and the current project doesn't 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 can't be written to.  Check that your TEMP environment variable is set to a valid directory and that the disk isn't full.


Error reading Tutorial file 'item
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.


One or more replacements too long and not made

A Replace operation 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 wasn't done and break the long statements into several lines.


Syntax errors produced while replacing

The Replace operation has introduced one or more syntax errors in the code and was therefore halted.  Choose Start from the Run menu so Visual Basic will identify the syntax error(s).


Can't find Windows Help .EXE file

The Windows Help application isn't available.  If WINHELP.EXE is on your machine, make sure it is on your path.  If it isn't on your machine, run Microsoft Windows setup to install it.


Invalid procedure name

A procedure name can't be a restricted keyword, must start with a letter, must be unique within the same scope, and can be a maximum of 255 characters [image] including letters, numbers, and underscores (_).  Function procedure names can include a type declaration character, but Sub procedure names can't.


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 Edit menu.


Not enough room to paste contents into current line

A line of Visual Basic code can't 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 Current Project by checking the appropriate box in the Search frame of the Find or Replace dialog box.


Array already has control at index 'item
Array already has control at index 'item'

Possible causes:

You tried to change the index value to a number that is already used by this control array.  To determine which indices have already been assigned, select the Index property in the Properties window for each control array element.

You tried to change the Name property of a control in an array to the name of a control array already using this index value.


Not a legal object name: 'item
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 the Name property of a form or control is 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 restricted keywords, can begin with a number, and can contain nonalphanumeric 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 name
'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 can't have the same name as any form in the same project.


Item' is a system object name
'Item' is a system object name

Screen, Clipboard, and Printer are the names of system objects, so they can't be used as form or control names.


Event handler must be a Sub procedure

A valid event procedure, such as Form_Click, must be a Sub procedure [image] it can't 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 noncontrol array can't take the index argument.  Check the control's Index property.  If it is not null, 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 for 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 doesn't 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 isn't 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 a shortcut key that has already been assigned to another menu item.  Assign a different shortcut key.


Separator may not be checked or disabled, or have a 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; but you can set their Visible property to False.


At least one submenu item must be visible

The Visible property can't be set to False for the last remaining visible submenu item.  You can't have a parent menu with no visible submenu items.


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.


Invalid command line argument 'item
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, choose OK.  To continue running your program, choose Cancel.


Save changes to 'item'?

This file has changed since it was last saved.  Choose Yes to save it, choose No to close the file without saving it, or choose Cancel if you don't want to close the file.


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

There isn't 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 isn't 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 can't 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.


Module 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 weren't 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 the Name property of a control 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 value one higher than the control previously created with this name.  If you don' want to create a control array, choose No.  If you're pasting a control, Visual Basic will generate the 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 triggers 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.


Replace existing 'item'?

A file with this name already exists.  Choose Yes to replace the file with the current file, or choose Cancel to stop the save operation.


Item' doesn't exist
'Item' doesn't exist

The file you specified doesn't exist in the specified directory.  Check that you have spelled the filename correctly and specified the correct directory.


Item' already exists in project
'Item' already exists in project

The file you specified is already part of the project.  You can't add the same file to a project more than once.  You can't save a file with the same name as another file in the project.


Item' has an old file format.  When saved it will be saved in a newer format.
'Item' has an old file format.  When saved it will be saved in a newer format.

This file was created with an earlier version of Visual Basic.  When you save it, it will be saved under the Visual Basic 4.0 file format.


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

Visual Basic couldn't load the code in this form file.  You can continue to load the form anyway or stop loading it.


Search string is 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 'item
Incompatible version created 'item'

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.


One or more files in the project have changed.  Do you wish to save the changes now?

One of the property settings or a code statement has changed for one or more of the files in the project and the changes have not yet been saved.  This is your last chance to save the changes before loading another project.


Text too long to edit

The current line is too long to edit.  The maximum length of the line is dependent upon the current state of Visual Basic and 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] use the Find command on the Edit menu (or SHIFT+F2) to 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 property setting 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 Name

This control is part of a control array.  If you want to delete its index value, which deletes it from the control array, you must first rename it with a unique Name property setting.


Item' is a control name

A control already has this name.  A form can't have the same name as a control in the same project.


Menu item 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 Editor dialog, 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, a Menu control requires you to assign names as the control is created, because Visual Basic doesn't 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 value to the item.  Unlike other control arrays in Visual Basic, Menu control arrays require you to assign indices as the item is created, because Visual Basic doesn't supply a default Index property setting for Menu control array items.


Menu control array indexes must be in ascending order

An index value assigned to an item in a Menu control array is out of order with the other items.  The indices of a Menu control array don't have to be contiguous (for example, 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 Menu control array in which the other items in the array are adjacent to the current item.  The indices of the items in a Menu control array don't have to be contiguous (for example, 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.


EXEName Property

Applies To

Returns the root name of the executable file (without the extension) that is currently running.  If running in the development environment, returns the name of the project.

Syntax

object.EXEName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


EXEName Property Applies To

App Object


Out of memory (31001)

Could not allocate or access enough memory or disk space for the specified operation.


position indicator <definition>
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 <definition>
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.


Load Picture, Load Icon Dialog Boxes

See Also

Loads an existing picture or icon file.

Dialog Box Options

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, *.EMF, *.ICO) [image] Lists all picture files.

Bitmaps(*.BMP, *.DIB) [image] Lists bitmaps and DIBs.

Metafiles (*.WMF, *.EMF) [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

Icon Property

Picture Property


Controls

See Also

A control is an object that you draw on a Form object to enable or enhance user interaction with an application.  You add menu controls to a form using the Menu Editor; 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 CommandButton control'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.

There are 26 basic tools in the Toolbox:

CheckBox Control

ComboBox Control

CommandButton Control

CommonDialog Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileListBox Control

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

Line Control

ListBox Control

Menu Control

OLE Container Control

OptionButton Control

PictureBox Control

Shape Control

TextBox Control

Timer Control

VScrollBar Control


 See Also

ActiveControl Property

ActiveForm Property

Controls Collection

Creating a Menu Bar

Drawing a Control

Toolbox


A default printer does not exist (Error 28663)

Check the system for installed printers using the Printers collection.  If there are printers installed, set the Printer object to one of the printers in the Printers collection to define a default printer.


An attempt to subclass a ListBox failed due to insufficient memory (Error 20478)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Cancel was selected (Error 32755)

This error occurs when the CancelError property is set to True and the user clicks the Cancel button in the dialog box.  Use this error to execute different code when the Cancel button was selected.  For example, in a File Open dialog box, you might respond to this error by exiting the current procedure instead of attempting to open a file.


Couldn't determine procedure address(es).  \nSelect a different DLL (Error 32753)
Couldn't determine procedure address(es).  Select a different DLL (Error 32753)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


DLL selected couldn't be loaded (Error 32754)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Help call fail.  Check Help properties (Error 32751)

Check to make sure the HelpContextID and HelpFile properties are set to proper values for the Help file used by the application.


Invalid filename (Error 20477)

The specified filename may not exist or may contain illegal characters.


Load of required resources failed (Error 28670)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


Low on memory!  Can't bring up the dialog! (Error 32752)

This error occurs when sufficient memory isn't available.  Check for sufficient system memory as well as available system resources.


No fonts exist (Error 24574)

Before displaying the Choose Font dialog box, you must set one of the following flags:

ScreenFonts

PrinterFonts

Both


No printer device drivers were found (Error 28664)

The system may not have printer drivers installed or the drivers may be missing.


The common dialog function failed during initialization (Error 32765)

This error often occurs when sufficient memory isn't available.


The common dialog function failed to find a specified string (Error 32761)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The common dialog function failed to load a specified resource (Error 32760)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The common dialog function failed to load a specified string (Error 32762)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The common dialog function failed to lock a specified resource (Error 32759)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


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

This error occurs when the information in WIN.INI can't be read by the CommonDialog control.  For example, the WIN.INI entry may contain the string "LDT1" instead of "LPT1" to identify a port.


The common dialog function was unable to allocate memory for internal data structures (Error 32758)

This error is caused by insufficient memory.


The common dialog function was unable to lock the memory associated with a handle (Error 32757)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The data in the DEVMODE and DEVNAMES data structures describes two different printers (Error 28662)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The ENABLEHOOK flag was set in the Flags member of a common dialog data structure but the application failed to provide a pointe
The ENABLEHOOK flag was set in the Flags member of a common dialog data structure but the application failed to provide a pointer to a corresponding hook function (Error 32756)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a co
The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a corresponding instance handle (Error 32763)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a co
The ENABLETEMPLATE flag was set in the Flags member of a common dialog data structure but the application failed to provide a corresponding template

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The FileName buffer is too small to store the selected file name(s) (Error 20476)

This error occurs when the MaxFileSize property is too small to allocate enough space in memory for the selected file name(s).  Increase the setting of the MaxFileSize property.


The lStructSize member of the corresponding common dialog data structure is invalid (Error 32766)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


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

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The PD_RETURNDEFAULT flag was set in the Flags member of the PRINTDLG data structure but either the hDevMode or hDevNames field
The PD_RETURNDEFAULT flag was set in the Flags member of the PRINTDLG data structure but either the hDevMode or hDevNames field was nonzero (Error 28668)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The PrintDlg function failed during initialization (Error 28665)

This error is usually caused by insufficient memory.


The PrintDlg function failed to load the specified printer's device driver (Error 28667)

This error could be caused by a defective printer driver or a corruption in system memory.

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


The PrintDlg function failed when it attempted to create an information context (Error 28661)

The amount of available system resources may be too low.


The printer device driver failed to initialization a DEVMODE data structure (Error 28666)
The printer device driver failed to initialize a DEVMODE data structure (Error 28666)

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.  This error only applies to printer drivers written for Windows version 3.0 or later.


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

The CommonDialog control uses specialized functions in the operating system to present the dialog boxes it displays.  When this error occurs, the problem exists at the operating system level and shouldn't appear as the result of Visual Basic code that uses the control.  If you receive this error message, contact Technical Support for assistance.


WhatsThisHelpID Property (Windows 95)

See Also	Applies To

Returns or sets an associated context number for an object.  Use to provide context-sensitive Help for your application using the What's This pop-up in Windows 95 Help.

Important   This property requires the Microsoft Windows 95 or Microsoft Windows NT 3.51 operating systems.

Syntax

object.WhatsThisHelpID [= number]

The WhatsThisHelpID property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A numeric expression specifying a Help context number, as described in Settings.

Settings

The settings for number are:

Setting	Description

0	(Default) No context number specified.

>0	An integer specifying the valid context number for the What's This topic associated with the object.

Remarks

Visual Basic applications can support either of two different models for context-sensitive Help.

Window 3.x

Windows 95

The Windows 3.x model uses the F1 key to start Windows Help and load the topic identified by the HelpContextID property.  The Windows 95 model typically uses the What's This button in the upper-right corner of the window to start Windows Help and load a topic identified by the WhatsThisHelpID property.  Use the WhatsThisHelp property to select between the two context-sensitive models.


See Also

HelpContextID Property

ShowWhatsThis Method

WhatsThisButton Property

WhatsThisMode Method

WhatsThisHelp Property


WhatsThisHelpID Property Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileLIstBox Control

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control

VScrollBar Control


WhatsThisButton Property (Windows 95)

See Also	Applies To

Returns or sets a value that determines whether the What's This button appears in the title bar of a Form object.  Read-only at run time.

Important   This property requires the Microsoft Windows 95 or Microsoft Windows NT 3.51 operating systems.

Syntax

object.WhatsThisButton

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The settings for the WhatsThisHelp property are:

Setting	Description

True	Turns display of the What's This Help button on.

False	(Default)  Turns display of the What's This Help button off.

Remarks

The WhatsThisHelp property must be True for the WhatsThisButton property to be True.  In addition, the following properties must also be set as shown:

ControlBox property = True

BorderStyle property = Fixed Single or Sizable

MinButton and MaxButton = False

Or:

BorderStyle property = Fixed Dialog


See Also

BorderStyle Property

ShowWhatsThis Method

WhatsThisMode Method

WhatsThisHelp Property

WhatThisHelpID Property


WhatsThisButton Property Applies To

Form object


WhatsThisHelp Property (Windows 95)

See Also	Applies To

Returns or sets a value that determines whether context-sensitive Help uses the What's This pop-up provided by Windows 95 Help or the main Help window.  Read-only at run time.

Important   This property requires the Microsoft Windows 95 or Microsoft Windows NT 3.51 operating systems.

Syntax

object.WhatsThisHelp [= boolean]

The WhatsThisHelp property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A value that determines if Help uses the What's This pop-up, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The application uses one of the What's This access techniques to start Windows Help and load a topic identified by the WhatsThisHelpID property.

False	(Default)  The application uses the F1 key to start Windows Help and load the topic identified by the HelpContextID property.

Remarks

There are three access techniques for providing What's This Help in an application.  The WhatsThisHelp property must be set to True for any of these techniques to work.

Providing a What's This button in the title bar of the form using the WhatsThisButton property.  The mouse pointer changes into the What's This state (arrow with question mark).  The topic displayed is identified by the WhatsThisHelpID property of the control clicked by the user.

Invoking the WhatsThisMode method of a form.  This produces the same behavior as clicking the What's This button without using a button.  For example, you can invoke this method from a command on a menu in the menu bar of your application.

Invoking the ShowWhatsThis method for a particular control.  The topic displayed is identified by the WhatsThisHelpID property of the control.


See Also

ShowWhatsThis Method

WhatsThisButton Property

WhatsThisMode Method

WhatsThisHelpID Property


WhatsThisHelp Property Applies To

Form Object

MDIForm Object


ShowWhatsThis Method (Windows 95)

See Also	Example	Applies To

Displays a selected topic in a Help file using the What's This popup provided by Windows 95 Help.

Important   This method requires the Microsoft Windows 95 or Microsoft Windows NT 3.51 operating systems.

Syntax

object.ShowWhatsThis

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The ShowWhatsThis method is very useful for providing context-sensitive Help from a context menu in your application.  The method displays the topic identified by the WhatsThisHelpID property of the object specified in the syntax.


See Also

WhatsThisButton Property

WhatsThisMode Method

WhatsThisHelp Property

WhatsThisHelpID Property


ShowWhatsThis Method Applies To

CheckBox Control

ComboBox Control

CommandButton Control

Data Control

DBCombo Control

DBGrid Control

DBList Control

DirListBox Control

DriveListBox Control

FileLIstBox Control

Frame Control

Grid Control

HScrollBar Control

Image Control

Label Control

ListBox Control

OLE Container Control

OptionButton Control

PictureBox Control

TextBox Control

VScrollBar Control


ShowWhatsThisMethod
ShowWhatsThis Method Example

This example displays the What's This Help topic for a CommandButton control by selecting a menu command from a context menu created for the button.

Private ThisControl As Control

Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, _

X As Single, Y As Single)

If Button = vbRightButton Then

Set ThisControl = Command1

PopupMenu mnuBtnContextMenu

End If

Set ThisControl = Nothing

End Sub

Private Sub mnuBtnWhatsThis_Click()

ThisControl.ShowWhatsThis

End Sub


WhatsThisMode Method (Windows 95)

See Also	Example	Applies To

Causes the mouse pointer to change into the What's This pointer and prepares the application to display What's This Help on the selected object.

Important   This method requires the Microsoft Windows 95 or Microsoft Windows NT 3.51 operating systems.

Syntax

object.WhatsThisMode

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Executing the WhatsThisMode method places the application in the same state you get by clicking the What's This button in the title bar.  The mouse pointer changes to the What's This pointer.  When the user clicks an object, the WhatsThisHelpID property of the clicked object is used to invoke the context-sensitive Help.  This method is especially useful when invoking Help from a menu in the menu bar of your application.


See Also

ShowWhatsThis Method

WhatsThisButton Property

WhatsThisHelp Property

WhatThisHelpID Property


WhatsThisMode Method Applies To

Form object

MDIForm object


WhatsThisModeMethod
WhatsThisMode Method Example

This example uses a command in a menu to change the mouse pointer to the What's This pointer and enable context-sensitive Help.  To try the example, create a menu, and paste the code into the Click event of one of the Menu controls.  Press F5, and click the menu command to toggle the application into the What's This state.

Private Sub mnuContextHelp_Click ()

Form1.WhatsThisMode

End Sub


ShowInTaskbar Property (Windows 95)

See Also	Applies To

Returns or sets a value that determines whether a Form object appears in the Windows 95 taskbar.  Read-only at run time.

Important   This property requires the Microsoft Windows 95 operating system or Microsoft Windows NT 3.51 operating systems.

Syntax

object.ShowInTaskbar

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Settings

The settings for the ShowInTaskbar property are:

Setting	Description

True	(Default)  The Form object appears in the taskbar.

False	The Form object does not appear in the taskbar.

Remarks

Use the ShowInTaskbar property to keep dialog boxes in your application from appearing in the taskbar.

The default value for the ShowInTaskbar property assumes the default setting for the BorderStyle property of the Form object (Sizable).  Changing the BorderStyle property may change the setting of the ShowInTaskbar property.


See Also

BorderStyle Property


ShowInTaskbar Property Applies To

Form object


Connecting Help to an Application

See Also

Part of a professional application is support for online information.  You can provide context-sensitive Help for your applications by creating Windows Help files which you connect to your application.  With context-sensitive Help, users of your application can choose a control displayed in the application and request information specifically about that control.

Choosing a Help Model

Visual Basic applications can support either of two different models for context-sensitive Help.

Windows 3.x

Windows 95

The Windows 3.x model uses the F1 key to start Windows Help and load a specific topic.  The Windows 95 model typically uses the What's This button in the upper-right corner of the window to start Windows Help and display a particular topic.  You specify which topic you want to display through a context ID, a number unique to each topic in a Windows Help file.

Choosing between these two models may depend on the operating systems you plan to support with your application.  If you plan to create both 16-bit and 32-bit versions of your application, you may want to consider using the Windows 3.x model.  Because Windows 95 Help provides full support for Windows 3.x Help files, you can use one model for 16-bit (Windows 3.x) and 32-bit (Windows 95 and Windows NT 3.51 or later) versions of your application.

If you only plan to create a 32-bit version of your application, you may want to support the Windows 95 Help model.  Because Windows NT 3.51 or later uses the same Help engine as Windows 95, you can use the most current Help engine while on both 32-bit Windows platforms.

Use the WhatsThisHelp property to select between the two context-sensitive models.

Defining the Help File

Specify the Help file you want your application to open using the HelpFile property.  HelpFile is a property of the App object, which contains global information about a Visual Basic project.

The value of the HelpFile property is a string that gives the name of the Help file the application opens when a user requests context-sensitive Help.  This string can be a full path and filename or only a filename.  If you specify a full path and filename, the application looks for the Help file in the specified directory.  If you specify only a filename, the application looks for the Help file in the current directory.

To specify a Help file for the HelpFile property

1.	From the Tools menu, choose Options.

2.	Select the Project options tab.

3.	From the list of project options, select Help File.

4.	In the Setting box, enter the name of the application's Help file.  You can enter a full path and filename or only a filename.  You can also click the button to the right of the Setting box to choose a file using a dialog box.

5.	Choose OK.

Note    To specify a Help file at run time, set the value of App.HelpFile to the name of the Help file.

Assigning Context IDs

Context IDs are numbers assigned to individual topics in a Windows Help file.  To provide context-sensitive Help in your application, you must:

1.	Decide which controls in your application will display a Help topic.

2.	Create Help topics that explain the use of each control in your application.

3.	Assign context IDs to both the Help topics in the compiled Windows Help file and to the corresponding controls in your application.

To assign the context IDs to controls in your application, you set the appropriate property of that control.  If you plan to use the Windows 3.x model for context sensitivity, assign the context ID to the HelpContextID property.  If you plan to use the Windows 95 model, assign the context ID to the WhatsThisHelpID property.  Make sure you set the WhatsThisHelp property to indicate which Help model your application supports.

Using Windows 95 Help Features

The Windows 95 Help model provides several ways to request context-sensitive information about elements of an application's user interface.  If you use the Windows 95 Help model in your application (by setting the WhatsThisHelp property to True), you need to consider the settings of several related properties.  The following table briefly summarizes these properties:

Property	Description

WhatsThisButton	Controls display of the What's This button in the title bar of a Form.  Users can click this button, then click a control in the application to request context-sensitive Help.

WhatsThisHelpID	Assigns the context ID number of a topic in the application's Help file to a particular control or Form in the application.

There are also a pair of methods you can use to support the Windows 95 Help model.  The following table briefly summarizes these methods:

Method	Description

ShowWhatsThis	Displays a specified Help topic as a What's This pop up.

WhatsThisMode	Puts the application in context-sensitive Help mode by changing the mouse pointer to a Help pointer.  The object clicked by the Help pointer causes its associated Help topic to appear.


See Also

HelpContextID Property

HelpFile Property

ShowWhatsThis Method

WhatsThisButton Property

WhatsThisHelp Property

WhatsThisMode Method

WhatThisHelpID Property


Creating Context Menus (Windows 95)

See Also	Example

A context menu is a floating menu displayed over a form or control, independent of the menu bar.  The items displayed on the context menu depend on where the pointer was located when the right mouse button was pressed.  In Windows 95, you activate context menus by clicking the right mouse button.  Applications that implement context menus usually display the menu when the user clicks the right mouse button.  You should use context menus to provide an efficient method for accessing common, contextual commands.

Use pop-up menus to create Windows 95 context menus in your application.  Windows 95 context menus differ from default pop-up menus in two ways:

May contain a bold command on the menu

Respond to both left and right mouse clicks

Using a Bold Command in a Context Menu

Context menus in Windows 95 applications often include a command that performs the same task when clicked, as when double-clicking on the object to which the context menu applies.  This special menu command in the context menu appears in bold as a visual cue to the user that they can either double-click the object, or select the bold menu command.

To support this design approach in your applications, create a procedure which executes the code assigned to both the Click event of the bold context menu command and the DblClick event of the object to which the context menu applies.  Then have both these event procedures call the shared code in the procedure you created.

Because the equivalent to selecting the bold command in the context menu is double-clicking an object, you should provide bold menu commands in context menus only for objects that have a DblClick event.

Responding to Left and Right Mouse Clicks

Under Windows 95, you can select a context menu command with either the left or right mouse buttons.  Under other versions of Windows, the pop-up menu responded only to the left mouse button.  To support this design approach, include the vbPopupMenuRightButton constant in the flags argument of the PopupMenu method.

Note  Windows 95 automatically provides a context menu for TextBox controls as well as the text box portion of a ComboBox control.  If you create your own context menus for these controls, the system-provided context menu appears first.   Your context menu appears after the system menu disappears.


See Also

PopupMenu Method


Context Menu Example

This example uses both the Click event of a Menu control in a context menu as well as the DblClick event of a Label control to toggle the font size of the Label.

Private Sub lblProgName_MouseUp (Button As Integer, Shift As Integer, _

X As Single, Y As Single)

If Button = vbRightButton Then

' Display the context menu on right mouse click.

PopupMenu mnuContextExample, vbPopupMenuRightButton, _

, , mnuToggleFontSize

End If

End Sub

Private Sub lblProgName_DblClick()

' Call the Sub used to toggle between large and small fonts.

ToggleFontSize

End Sub

Private Sub mnuToggleFontSize_Click()

' Call the Sub used to toggle between large and small fonts.

ToggleFontSize

End Sub

Private Sub ToggleFontSize()

Select Case mnuToggleFontSize.Caption

Case "Small Font"

' Decrease the font size.

lblProgName.Font.Size = 10

' Change label caption to toggle to a large font.

mnuToggleFontSize.Caption = "Large Font"

Case "Large Font"

' Increase the font size.

lblProgName.Font.Size = 14

' Change label caption to toggle to a small font.

mnuToggleFontSize.Caption = "Small Font"

End Select

End Sub


Using Custom Properties Dialog Boxes

See Also

When setting the properties of a custom control, you may need or prefer to use the control's custom properties dialog box.  This dialog box provides an alternative to the list of properties in the Properties window for setting control properties at design time.

Two Ways to Set Properties

The reason for the custom properties dialog box is that not all applications that use custom controls provide a Properties window like the one in Visual Basic.  The dialog box provides an interface for setting key control properties regardless of the interface supplied by the hosting application.

For some control properties, you choose either of these two locations to set the property:

The Properties window

The custom properties dialog box

In some cases, the dialog box is the only way to set a property at design time.  This is usually the situation when the interface needed to set a property doesn't work inside the Properties window.  For example, assigning a series of images to an ImageList control involves more than typing the name of a file or choosing from a list.

Finding the Dialog Box

Not all custom controls provide a custom properties dialog box.  To see whether a control provides this dialog box, scroll the list of properties in the Properties Window to the top.  If the list of properties contains the name (Custom), then the control provides the dialog box.

Using the Dialog Box

After you choose the (Custom) entry in the Properties window, click the Properties button to display the control's custom properties dialog box, often presented as a tabbed dialog box.  Choose the tab that contains the interface for setting the properties that you want to set.

After you make changes in one tab, you can often apply those changes immediately by clicking the Apply button (if provided).  You can click other tabs to set other properties as needed.  To approve all changes made in the dialog box, click the OK button.  To return to the Properties window without changing any property settings, click the CANCEL button.


See Also

Properties Window

Using Custom Controls


OLERequestPendingMsgText Property

See Also	Applies To

Returns or sets the text of the alternate "busy" message displayed when mouse or keyboard input is received while an OLE Automation request is pending.  Not available at design time.

Syntax

object.OLERequestPendingMsgText [ = string]

The OLERequestPendingMsgText property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression that evaluates to the message text that will be displayed in the alternate message box for the OLE request pending condition.

Remarks

Visual Basic displays a default Server Busy dialog box when mouse or keyboard input is received while an OLE Automation request is pending.  This dialog box includes text and a Switch To button which are intended for use with visible OLE servers such as Microsoft Excel.  There are situations in which the default dialog box may not meet your needs:

Your program may call a method of an object provided by an OLE server that has no user interface.  OLE servers created using Visual Basic Professional edition, for example, may run in the background without any visible forms.

The OLE server you call may have been created using the Remote Automation features of Visual Basic, Enterprise edition, and may be running on another computer located at some distance from the user.

If your program has loaded a Microsoft Excel workbook using the GetObject function, the workbook will not be visible when the user switches to Microsoft Excel.  In fact, Microsoft Excel itself may not be visible, in which case the Switch To button does nothing.

In these situations, the default text and Switch To button are inappropriate and may confuse the user of your program.

The OLERequestPendingMsgText property allows you to replace the default Server Busy dialog box with an alternate message box.  Setting OLERequestPendingMsgText to your own message string causes the default Server Busy dialog box to be replaced by a simple message box containing your message text and an OK button.

Note   Once an OLE Automation request has been accepted by an OLE server, there is no way to cancel it.

If OLERequestPendingMsgText is equal to an empty string (""), the default Server Busy dialog is displayed.

Important   When you know that an OLE Automation request may take more than a few seconds, and you are using a hidden or remote OLE server, you should set an alternate message.  For remote OLE servers, the alternate message is recommended for all requests.  Network traffic may occasionally cause even a very short OLE request to take several seconds.


See Also

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgText Property

OLEServerBusyMsgTitle Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property


OLERequestPendingMsgText Applies To

App Object


OLERequestPendingMsgTitle Property

See Also	Applies To

Returns or sets the caption of the alternate "busy" message displayed when mouse or keyboard input is received while an OLE Automation request is pending.  Not available at design time.

Syntax

object.OLERequestPendingMsgTitle [= string]

The OLERequestPendingMsgTitle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression that evaluates to the caption of the alternate message box for the OLE request pending condition.

Remarks

If the OLERequestPendingMsgText property has been set, the value of the OLERequestPendingMsgTitle property is used as the caption of the alternate "busy" message.  The default value of the OLERequestPendingMsgTitle property is the current value of the Title property of the App object.  This is the recommended setting.

If the OLERequestPendingMsgText property is set to an empty string (""), the OLERequestPendingMsgTitle property is ignored.


See Also

OLERequestPendingMsgText Property

OLERequestPendingTimeout Property

OLEServerBusyMsgText Property

OLEServerBusyMsgTitle Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property


OLERequestPendingMsgTitle Applies To

App Object


OLERequestPendingTimeout Property

See Also	Applies To

Returns or sets the number of milliseconds that must elapse before a "busy" message can be triggered by mouse or keyboard input received while an OLE Automation request is pending.  Not available at design time.

Syntax

object.OLERequestPendingTimeout [= milliseconds]

The OLERequestPendingTimeout property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

milliseconds	A Long integer representing the number of milliseconds that must elapse before a busy message can be triggered.

Remarks

The default value of this property is 5000 milliseconds (five seconds).

Important   This time-out value also affects documents you link or embed using the OLE container control or the Toolbox.  If you are using linked or embedded documents and you change this property before an OLE Automation request, it is a good idea to reset the value afterward.


See Also

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLEServerBusyMsgText Property

OLEServerBusyMsgTitle Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property


OLERequestPendingTimeout Applies To

App Object


OLEServerBusyMsgText Property

See Also	Applies To

Returns or sets the text of the alternate "busy" message which is displayed if an OLE server rejects an OLE Automation request.  Not available at design time.

Syntax

object.OLEServerBusyMsgText [= string]

The OLEServerBusyMsgText property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression that evaluates to the message text that will be displayed in the alternate message box for the OLE server busy condition.

Remarks

Visual Basic continues to retry an OLE Automation request for the number of milliseconds specified by the OLEServerBusyTimeout property.  If the OLE  server has not accepted the request in that interval, Visual Basic displays a default Server Busy dialog box.  This dialog box includes text and a Switch To button which are intended for use with visible OLE servers such as Microsoft Excel.  There are situations in which the default dialog box may not meet your needs:

Your program may call a method of an object provided by an OLE server that has no user interface.  OLE servers created using Visual Basic Professional edition, for example, may run in the background without any visible forms.

The OLE server you call may have been created using the Remote Automation features of Visual Basic, Enterprise edition, and may be running on another computer located at some distance from the user.

If your program has loaded a Microsoft Excel workbook using the GetObject function, the workbook will not be visible when the user switches to Microsoft Excel.  In fact, Microsoft Excel itself may not be visible, in which case the Switch To button does nothing.

In these situations, the default text and Switch To button are inappropriate and may confuse the user of your program.

The OLEServerBusyMsgText property allows you to replace the default Server Busy dialog box with an alternate message box.  Setting OLEServerBusyMsgText to your own message string causes the default Server Busy dialog box to be replaced by a simple message box containing your message text, an OK button, and a Cancel button.

If OLERequestPendingMsgText is equal to an empty string (""), the default Server Busy dialog is displayed.

If the user presses the Cancel button of the default Server Busy dialog box or the alternate message box, the OLE error -2147418111 (&h80010001) is raised in the procedure that made the OLE Automation request.

Important   When you know that an OLE Automation request may take more than a few seconds and you are using a hidden or remote OLE server, you should set an alternate message.  For remote OLE servers, the alternate message is recommended for all requests.  Network traffic may occasionally cause even a very short OLE request to take several seconds.


See Also

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgTitle Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property


OLEServerBusyMsgText Applies To

App Object


OLEServerBusyMsgTitle Property

See Also	Applies To

Returns or sets the caption of the alternate "busy" message which is displayed when an OLE server rejects an OLE Automation request.  Not available at design time.

Syntax

object.OLEServerBusyMsgTitle [= string]

The OLEServerBusyMsgTitle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

string	A string expression that evaluates to the caption of the alternate message box for the OLE server busy condition.

Remarks

If the OLEServerBusyMsgText property has been set, the value of the OLEServerBusyMsgTitle property is used as the caption of the alternate busy message.  The default value of the OLEServerBusyMsgTitle property is the current value of the Title property of the App object.  This is the recommended setting.

If the OLEServerBusyMsgText property is set to an empty string (""), the OLEServerBusyMsgTitle property is ignored.


See Also

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgText Property

OLEServerBusyRaiseError Property

OLEServerBusyTimeout Property


OLEServerBusyMsgTitle Applies To

App Object


OLEServerBusyRaiseError Property

See Also	Applies To

Determines whether a rejected OLE Automation request raises an error, instead of displaying a "busy" message.  Not available at design time.

Syntax

object.OLEServerBusyRaiseError [ = boolean]

The OLEServerBusyRaiseError property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression that specifies whether an error is to be raised, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	An error is raised when the number of milliseconds specified by the OLEServerBusyTimeout property have elapsed.

False 	Depending on the setting of the OLEServerBusyMsgText property, either the default Server Busy dialog box or an alternate busy message will be displayed.

Remarks

Raising an error when an OLE server rejects an OLE Automation request returns control to your program, which allows you to provide your own custom dialog box in place of either the default Server Busy dialog box or the alternate busy message.

The OLE Automation error that will be raised is -2147418111 (&h80010001).


See Also

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgTitle Property

OLEServerBusyMsgText Property

OLEServerBusyTimeout Property


OLEServerBusyRaiseError Applies To

App Object


OLEServerBusyTimeout Property

See Also	Applies To

Returns or sets the number of milliseconds during which an OLE Automation request will continue to be retried, before a "server busy" message is displayed.  Not available at design time.

Syntax

object.OLEServerBusyTimeout [= milliseconds]

The OLEServerBusyTimeout property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

milliseconds	A Long integer representing the number of milliseconds during which an OLE Automation request will be retried.

Remarks

The default value of this property is 10000 milliseconds (ten seconds).

Important   This time-out value also affects documents you link or embed using the OLE container control or the Toolbox.  If you are using linked or embedded documents and you change this property before an OLE Automation request, it is a good idea to reset the value afterward.


See Also

OLERequestPendingMsgText Property

OLERequestPendingMsgTitle Property

OLERequestPendingTimeout Property

OLEServerBusyMsgTitle Property

OLEServerBusyMsgText Property

OLEServerBusyRaiseError Property


OLEServerBusyTimeout Applies To

App Object


Main can't be module, type, project, or form name.

You have the startup form set to Sub Main, and you have a module, form, project, or type named "Main" which prevents the Sub with the same name from being called.

Rename the module, form, project, or type.


The action was canceled by an associated object.
The action was canceled by an associated object. (Error 3426)

The Data control was trying to complete an action and a control or object bound to the Data control canceled the action.

This occurs when the user cancels the action. For example, if you place a DBGrid on a form and bound it to the Data control, and then the user sets the Validate event in the Data control to Action = 0.  This causes cancellation of the operation.  It would also occur if DBGrid's BeforeUpdate event is set to Cancel = 1, canceling the action.

Placing error trapping code in the error event is one way of handling this error.


Can't put check mark here.

This is a menu design error indicating that you tried to select Checked on a menu item that does not support check marks.

For example, you

1.	Tried to select Checked in the Menu Editor for a top-level menu item.

2.	Selected Checked for some menu item which has a submenu such as a cascading sub-menu.

3.	Chose some menu such as a MDI Window list menu that cannot be checked.


The 'Class1' class module was found in the Compatible OLE Server, but not in the current file.

There is an incompatibility between the current project and the Compatible OLE Server.  This error has the following causes and solutions:

Changing the name of the project.

The Name property of the current project 'project1' is different from the name of the Compatible OLE Server 'server1'.  To avoid this incompatibility, change the Project Name, or clear the Compatible OLE Server setting by choosing Option command from the Tool menu, and then selecting the Project tab.

A class module was removed, made non-public, or renamed.

You can add the 'Class1' class to the project, make it public, or rename it to the original name.  If you choose the Accept button, the project will no longer support OLE Automation controllers which access the 'Class1' class and were compiled against the Compatible OLE Server.  To avoid this incompatibility, add the 'Class1' class to the project, or clear the Compatible OLE Server setting by choosing Option command from the Tool menu, and then selecting the Project tab.

A subroutine in a class module had an argument or return type change, or the number of arguments that has changed.

'Member1' in the 'Class1' class module has arguments and/or a return type that is incompatible with a similar declaration in the Compatible OLE Server.  If you choose the Accept button, the 'Class1' class module will no longer support OLE Automation controllers compiled against the Compatible OLE Server.  To avoid this incompatibility, edit the declaration to be compatible, or clear the Compatible OLE Server setting by choosing Option command from the Tool menu, and then selecting the Project tab.

A subroutine had been deleted or renamed.

The 'subroutine1' member was found in the 'Class1' class module of the Compatible OLE Server, but not in the current project.

If you choose the Accept button, the 'Class1' class module will no longer support OLE Automation controllers compiled against the Compatible OLE Server.  To avoid this incompatibility, add the declaration back into the class module, or clear the Compatible OLE Server setting by choosing Option command from the Tool menu, and then selecting the Project tab.

You can use the following buttons to accomplish these actions.

Use the:	To:

Accept button 	Indicate that you understand this incompatibility and want to continue compiling. The project will no longer support OLE Automation Controllers which access the 'Class1' class and were compiled against the Compatible OLE Server.

Compatibility is maintained on a per .EXE and per .DLL basis, so an incompatibility in any public class affects all public classes.

Any separate incompatibility will still show the dialog box.

Accept All button 	Indicate that you understand this incompatibility and want to continue compiling.  The project will no longer support OLE Automation Controllers which access the 'Class1' class and were compiled against the Compatible OLE Server. Compatibility is maintained on a per .EXE and per .DLL basis, so an incompatibility in any public class affects all public classes.

You will not see the dialog box for any further incompatibilities nor will you be warned again until the next time you use the Make EXE File or the Make OLE File command from the File menu, or re-load the project.

Declaration button 	Show a box containing the full text of the Declaration of the procedure or member.  You can try to undo the change that produced the incompatibility.  This only available if a subroutine in a class module has an argument or return type change or if a subroutine has been deleted or renamed.

Edit button 	Stop the compilation and go to the line of code that contains the incompatibility.  There are some changes where there is no applicable line of code.  For example, there is no applicable line of code for changing the name of the project.


Wrong version of operating system; requires Windows NT 3.51 (build 944 or above).

To run this version of Visual Basic, you must be running Windows NT version 3.51, build 944 or later.


Failure to replicate database; can't determine whether database is open in exclusive mode. (Error 3578)

This is an unexpected error. Please contact Microsoft Product Support Services for further information.


Unable to load control

This error occurs when you try to load a 16-bit version of a custom control into the 32-bit version of Visual Basic or when you try to load a 32-bit version of a custom control in the the 16-bit version of Visual Basic.  Locate the version of the custom control that is appropriate for the version of Visual Basic you are using and load that version of the control.


TaskVisible Property

See Also	Applies To

Returns or sets a value that determines if the application appears in the Windows task list.

Syntax

object.TaskVisible [= boolean]

The TaskVisible property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A boolean expression that determines if the application appears in the task list, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	(Default)  The application appears in the Windows task list.

False	The application does not appear in the Windows task list.

Remarks

The TaskVisible property can only be set to False in applications that do not display an interface, such as OLE servers that do not contain or display Form objects.  While the application displays an interface, the TaskVisible property is automatically set to True.


See Also

ShowInTaskbar Property


TaskVisible Property Applies To

App Object


hInstance Property

See Also	Applies To

Returns a handle to the instance of the application.

Syntax

object.hInstance

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The hInstance property returns an integer value in applications created with the 16-bit version of Visual Basic and a long value in applications created with the 32-bit version.

When working with a project in the Visual Basic development environment, the hInstance property returns the instance handle of the Visual Basic instance.


See Also

hWnd Property

hDC Property


hInstance Property Applies To

App Object


ColIsVisible Property

See Also	Applies To

Returns a value that indicates whether a specified column in a Grid control is currently visible.

Syntax

object.ColIsVisible(index)

The ColIsVisible property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

Index	An integer that specifies a column in the Grid control.  The value must be in the range of 0 to Cols property - 1.

Return Values

The return values for the ColIsVisible property are:

Setting	Description

True 	The specified column is currently visible.

False 	The specified column is not currently visible.


See Also

Cols, Rows Properties

RowIsVisible Property


ColIsVisible Property Applies To

Grid Control


ColPos Property

See Also	Applies To

Returns a value indicating the distance between the upper-left corner of a Grid control to the upper-left corner of a specified column.

Syntax

object.ColPos(index)

The ColPos property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

Index	An integer that specifies a column in the Grid control.  The value must be in the range of 0 to Cols property - 1.

Remarks

The value returned by the ColPos property specifies the distance in twips.


See Also

Cols, Rows Properties

RowPos Property


ColPos Property Applies To

Grid Control


RowIsVisible Property

See Also	Applies To

Returns a value that indicates whether a specified row in a Grid control is currently visible.

Syntax

object.RowIsVisible(index)

The RowIsVisible property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

Index	An integer that specifies a row in the Grid control.  The value must be in the range of 0 to Rows property - 1.

Return Values

The return values for the RowsVisible property are:

Setting	Description

True 	The specified row is currently visible.

False 	The specified row is not currently visible.


RowIsVisible Property Applies To

Grid Control


See Also

ColIsVisible Property

Cols, Rows Properties


RowPos Property

See Also	Applies To

Returns a value indicating the distance between the upper-left corner of a Grid control to the upper-left corner of a specified row.

Syntax

object.RowPos(index)

The RowPos property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

Index	An integer that specifies a row in the Grid control.  The value must be in the range of 0 to Rows property minus 1.

Remarks

The value returned by the RowPos property specifies the distance in twips.


See Also

ColPos Property

Cols, Rows Properties


RowPos Property Applies To

Grid Control


Comments Property

See Also	Applies To

Returns or sets a string containing comments about the running application.  Read only at run time.

Syntax

object.Comments

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Set this property at design time using the EXE Options dialog box.


See Also

CompanyName Property

EXE Options Dialog Box

FileDescription Property

LegalCopyright Property

LegalTrademarks Property

ProductName Property


Comments Property Applies To

App Object


CompanyName Property

See Also	Applies To

Returns or sets a string value containing the name of the company or creator of the running application.  Read only at run time.

Syntax

object.CompanyName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Set this property at design time using the EXE Options dialog box.


See Also

Comments Property

EXE Options Dialog Box

FileDescription Property

LegalCopyright Property

LegalTrademarks Property

ProductName Property


CompanyName Property Applies To

App Object


FileDescription Property

See Also	Applies To

Returns or sets a string value containing file description information about the running application.  Read only at run time.

Syntax

object.FileDescription

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Set this property at design time using the EXE Options dialog box.


See Also

Comments Property

CompanyName Property

EXE Options Dialog Box

LegalCopyright Property

LegalTrademarks Property

ProductName Property


FileDescription Property Applies To

App Object


LegalCopyright Property

See Also	Applies To

Returns or sets a string value containing legal copyright information about the running application.  Read only at run time.

Syntax

object.LegalCopyright

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Set this property at design time using the EXE Options dialog box.


See Also

Comments Property

CompanyName Property

EXE Options Dialog Box

FileDescription Property

LegalTrademarks Property

ProductName Property


LegalCopyright Property Applies To

App Object


LegalTrademarks Property

See Also	Applies To

Returns or sets a string value containing legal trademark information about the running application.  Read only at run time.

Syntax

object.LegalTrademarks

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Set this property at design time using the EXE Options dialog box.


See Also

Comments Property

CompanyName Property

EXE Options Dialog Box

FileDescription Property

LegalCopyright Property

ProductName Property


LegalTrademarks Property Applies To

App Object


Major Property

See Also	Applies To

Returns or sets the major release number of the project.  Read only at run time.

Syntax

object.Major

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The value of the Major property is in the range from 0 to 9999.

This property provides version information about the running application.  You set this property at design time in the EXE Options dialog box.


See Also

EXE Options Dialog Box

Minor Property

Revision Property


Major Property Applies To

App Object


Minor Property

See Also	Applies To

Returns or sets the minor release number of the project.  Read only at run time.

Syntax

object.Minor

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The value of the Minor property is in the range from 0 to 9999.

This property provides version information about the running application.  You set this property at design time in the EXE Options dialog box.


See Also

EXE Options Dialog Box

Major Property

Revision Property


Minor Property Applies To

App Object


ProductName Property

See Also	Applies To

Returns or sets a string value containing the product name of the running application.  Read only at run time.

Syntax

object.ProductName

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Set this property at design time using the EXE Options dialog box.


See Also

Comments Property

CompanyName Property

EXE Options Dialog Box

FileDescription Property

LegalCopyright Property

LegalTrademarks Property


ProductName Property Applies To

App Object


Revision Property

See Also	Applies To

Returns or sets the revision version number of the project.  Read only at run time.

Syntax

object.Revision

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The value of the Revision property is in the range from 0 to 9999.

This property provides version information about the running application.  You set this property at design time in the EXE Options dialog box.


See Also

EXE Options Dialog Box

Major Property

Minor Property


Revision Property Applies To

App Object


IconState Property (Add-In)

See Also	Applies To

Returns or sets a value indicating the status of a file in a project.

Syntax

object.IconState [= value ]

The IconState property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant that determines the file status, as described in Settings.

Settings

The settings for value are:

Constant	Value	Description

vbextSCCStatusControlled	1	File is under source code control.

vbextSCCStatusCheckedOut	2	File is checked out to current user.

vbextSCCStatusOutOther	4	File is checked out to another user.

vbextSCCStatusOutOfDate	32	The file is not the most recent.

vbextSCCStatusShared	512	File is shared between projects.


See Also

AddFile Method (Add-In)

CheckIn Event (Add-In)

CheckOut Event (Add-In)

FileCount Property(Add-In)

FileNames Property (Add-In)

Reload Method (Add-In)

SaveAs Method (Add-In)


IconState Property (Add-In) Applies To

Component Object (Add-In)


Reload Method (Add-In)

See Also	Applies To

Reloads the specified component from disk, discarding any unsaved changes.  Doesn't support named arguments.

Syntax

object.Reload

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Cursor position, code window and form visibility are not affected by the Reload method.  Reload doesn't change the setting indicating whether the project was edited since the last time it was saved.


See Also

InsertFile Method (Add-In)

FileCount Property (Add-In)

FileNames Property (Add-In)

IsDirty Property (Add-In)


Reload Method (Add-In) Applies To

Component Object


AfterNewProject Event (Add-In)

See Also	Applies To

Occurs when a new project is created or loaded.

Syntax

Sub AfterNewProject(projectname As String)

The projectname placeholder represents a string expression specifying the name of the project that was added.


See Also

Fetch Event (Add-In)

CheckIn Event (Add-In)

CheckOut Event (Add-In)

ConnectEvents Method (Add-In)

UnCheckOut Event (Add-In)

IconState Property (Add-In)


AfterNewProject Event (Add-In) Applies To

FileControl Object (Add-In)


CheckIn Event (Add-In)

See Also	Applies To

Occurs when the user chooses the Check In command from the Tools menu.

Syntax

Sub _CheckIn()

Remarks

The Check In command is enabled when the ProjectTemplate object's ConnectEvents method is enabled.


See Also

Fetch Event (Add-In)

AfterNewProject Event (Add-In)

CheckOut Event (Add-In)

ConnectEvents Method (Add-In)

UnCheckOut Event (Add-In)

IconState Property (Add-In)


CheckIn Event (Add-In) Applies To

ProjectTemplate Object (Add-In)


CheckOut Event (Add-In)

See Also	Applies To

Occurs when the user chooses the Check Out command from the Tools menu.

Syntax

Sub CheckOut()

Remarks

The Check Out command is enabled when the ProjectTemplate object's ConnectEvents method is enabled.


See Also

AfterNewProject Event (Add-In)

CheckIn Event (Add-In)

ConnectEvents Method (Add-In)

Fetch Event (Add-In)

IconState Property (Add-In)

UnCheckOut Event (Add-In)


CheckOut Event (Add-In) Applies To

ProjectTemplate Object (Add-In)


Fetch Event (Add-In)

See Also	Applies To

Occurs when the user chooses the Get command from the Tools menu.

Syntax

Sub Fetch()

Remarks

The Get command is enabled when the ProjectTemplate object's ConnectEvents method is enabled.


See Also

AfterNewProject Event (Add-In)

CheckIn Event (Add-In)

CheckOut Event (Add-In)

ConnectEvents Method (Add-In

UnCheckOut Event (Add-In)

IconState Property (Add-In)


Fetch Event (Add-In) Applies To

ProjectTemplate Object (Add-In)


LoadProject Method (Add-In)

See Also	Applies To

Loads the specified project without saving any changes to the current project, and returns the new ProjectTemplate object referring to the project.  Doesn't support named arguments.

Syntax

object.LoadProject(filename As String, replacecurrent As Boolean) As ProjectTemplate

The LoadProject method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

filename	Required.  A string expression specifying the filename of the project you want to load.  An empty string (" ") reloads the current project.

replacecurrent	Required.  A Boolean expression that determines whether the new project replaces the current project or is added to it.  Must be True.


See Also

AfterNewProject Event (Add-In)

Reload Method (Add-In)


LoadProject Method (Add-In) Applies To

Application Object (Add-In)


ReadOnlyMode Property (Add-In)

See Also	Applies To

Returns or sets a value that determines how the Visual Basic development environment interacts with read-only files.

Syntax

object.ReadOnlyMode [= value]

The ReadOnlyMode property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A value or constant that determines the project status, as described in Settings.

Settings

The settings for value are:

Value	Description

1	Strict.  Remove File and Add File commands are not available if the project file is read-only on the disk.  Windows and forms can be moved, but changes will not be saved.  For files which are also read-only on disk, the Code Window is read-only, controls cannot be added or removed, control positions are locked, and custom properties dialog boxes are disabled.

0	Lenient.  Modifications can be made to code, forms, and the project if files are read-only, but changes can't be saved back to the files.


See Also

IconState Property (Add-In)


ReadOnlyMode Property (Add-In) Applies To

Application Object


UnCheckOut Event (Add-In)

See Also	Applies To

Occurs when the user chooses the UnDo CheckOut command from the Tools menu.

Syntax

Sub UnCheckOut( )

Remarks

The UnCheckOut command is enabled when the ProjectTemplate object's ConnectEvents method is enabled.


See Also

AfterNewProject Event (Add-In)

CheckIn Event (Add-In)

CheckOut Event (Add-In)

ConnectEvents Method (Add-In)

Fetch Event (Add-In)

IconState Property (Add-In)


UnCheckOut Event (Add-In) Applies To

ProjectTemplate Object (Add-In)


ReadProperty Function (Add-In)

See Also	Applies To

Returns a string from the specified user-defined section and key in the project's .VBP file.

Syntax

object.ReadProperty (section As String, key As String) As String

The ReadProperty function syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

section	A string expression containing the name of the section where the key is found.

key	A string expression containing the name of the key to return.

Remarks

If section or key is empty or doesn't exist, you'll get the run-time error (5) Illegal function call.


See Also

WriteProperty Method (Add-In)

Properties Property (Add-In)

Property Object, Properties Collection (Add-In)


ReadProperty Function (Add-In) Applies To

ProjectTemplate Object (Add-In)


Creating Add-Ins

See Also

Microsoft Visual Basic gives you the ability to design and implement add-ins to the development environment.  You can use add-ins to add custom items to Visual Basic menus, to manipulate the active form and its controls, and to respond to a variety of file control events.

Three sample applications implementing add-ins are included under the SAMPLES directory in the ALIGN, DATAWIZ and SPY directories.

ActiveProject Property (Add-In)

Add Method (Add-In)

AddFile Method (Add-In)

AddFormTemplate Method (Add-In)

AddInMenu Property (Add-In)

AddMDIFormTemplate Method (Add-In)

AddMenu Method (Add-In)

AddMenuTemplate Method (Add-In)

AddReference Method (Add-In)

AddToolboxProgID Method (Add-In)

AddToolboxTypelib Method (Add-In)

AddToolboxVBX Method (Add-In)

AfterAddFile Event (Add-In)

AfterChangeFileName Event (Add-In)

AfterClick Event (Add-In)

AfterCloseFile Event (Add-In)

AfterNewProject Event (Add-In)

AfterRemoveFile Event (Add-In)

AfterWriteFile Event (Add-In)

Application Object (Add-In)

Application Property (Add-In)

BeforeLoadFile Event (Add-In)

CheckIn Event (Add-In)

CheckOut Event (Add-In)

ClassName Property (Add-In)

Component Object, Components Collection (Add-In)

ConnectEvents Method (Add-In)

Container Property (Add-In)

ControlTemplate Object, ControlTemplates Collection (Add-In)

ControlTemplates Property (Add-In)

DisconnectAddIn Event (Add-In)

DisconnectEvents Method (Add-In)

DoGetAddFileName Event (Add-In)

DoGetNewFileName Event (Add-In)

DoGetOpenProjectName Event (Add-In)

Fetch Event (Add-In)

FileControl Object (Add-In)

FileControl Property (Add-In)

FileCount Property (Add-In)

FileNames Property (Add-In)

FormTemplate Object (Add-In)

FullName Property (Add-In)

IconState Property (Add-In)

IndexedValue Property (Add-In)

InsertFile Method (Add-In)

IsDirty Property (Add-In)

Item Method (Add-In)

LastUsedPath Property (Add-In)

LoadProject Method (Add-In)>Main

MenuItems Collection (Add-In)

MenuItems Property (Add-In)

MenuLine Object (Add-In)

NewEnum Property (Add-In)

NumIndices Property (Add-In)

ProjectTemplate Object (Add-In)

Properties Property (Add-In)

Property Object, Properties Collection (Add-In)

ReadOnlyMode Property (Add-In)

ReadProperty Function (Add-In)

Reload Method (Add-In)

Remove Method (Add-In)

RemoveComponent Method (Add-In)

RequestChangeFileName Event (Add-In)

RequestWriteFile Event (Add-In)

SaveAs Method (Add-In)

SelectedComponents Collection (Add-In)

SelectedComponents Property (Add-In)

SelectedControlTemplates Collection (Add-In)

SelectedControlTemplates Property (Add-In)

SubMenu Object (Add-In)

UnCheckOut Event (Add-In)

Value Property (Add-In)

Version Property (Add-In)

WriteProperty Method (Add-In)


 See Also

Connecting An Add-in to Visual Basic

Working With Add-in Objects


Connecting an Add-in to Visual Basic

See Also

Visual Basic allows you to select and manage add-ins, which are extensions to the Visual Basic development environment.  You can use add-ins to add custom items to Visual Basic menus, to manipulate the active form and its controls, and to respond to a variety of file control events.

1.	Open a new project.  To use add-in objects in code, add a reference to VBIDE [image] Microsoft Visual Basic Development Environment using the References command on the Tools menu.

2.	Insert a class module.  Set the Instancing Property of the class module to Cre atable SingleUse or to Creatable MultiUse.  Set the Public property to True.  Set the Name property to a name identifying your add-in.

3.	Add declarations in the class module for the ConnectAddIn and DisconnectAddIn events.  Use the ConnectAddIn event to add menus to the Visual Basic development environment.  Use the DisconnectAddIn event to delete menus and perform other cleanup work in the development environment.

4.	To change the name for your add-in listed in the Add-In Manager: open the Object Browser, select the class module containing the ConnectAddIn and DisconnectAddIn events, select Options, and enter a name in the Description field of the Member Options dialog box.

5.	Write code adding a listing to the VB.INI file.  This code should add the listing to either or both the [Add-Ins16] and [Add-Ins32] sections of VB.INI.  Use the syntax projectname.classmodulename = 1 or 0 for the setting.  If 0, the add-in is listed in the Add-In Manager.  If 1, the add-in always loads on development environment startup.

It is ideal to have your add-in put itself in VB.INI.  You can find examples of this code in the sample applications DFD.VBP in the DATAWIZ directory, ALIGN.VBP in the ALIGN directory, and SPY.VBP in the SPY directory.  You can also use NotePad or another text editor and add this text manually to VB.INI.

6.	Run the application and open a second instance of Visual Basic.  In this second instance, from the Add-Ins selection on the Tools menu select Add-In Manager, then select the new add-in from the Add-In Manager dialog box.  At this point the add-in might open up a new form with its own interface, or might simply add items to the Add-Ins selection on the Tools menu.

7.	After the add-in is debugged, compile it to an .EXE file, or an in-process server DLL.


See Also

ConnectAddIn Event (Add-In)

Creating Add-Ins

DisConnectAddIn Event (Add-In)

Working with Add-In Objects


Working with Add-In Objects

See Also

Visual Basic provides three categories of objects you can use to develop add-ins: objects for adding new menus and responding to menu selections; objects for creating, opening and closing files in a project; objects for manipulating forms and controls in a project.

Inserting Visual Basic menu items

Use the SubMenu object, the MenuItems collection, and the MenuLine object to add and manipulate new menu items.  Use the AddInMenu property to add menus and commands to the Add-Ins menu.

Manipulating files in Visual Basic

Use the FileControl object to manipulate files in a Visual Basic project.  FileControl events provide notification of any change to a project file.  Use FileControl methods to connect other Visual Basic objects to file control events.

Manipulating forms and controls

A variety of objects allow you to enumerate and manipulate the objects included in a project:

ProjectTemplate Object

SelectedComponents Collection

Component Object

Components Collection

FormTemplate Object

ControlTemplates Collection

SelectedControlTemplates Collection (Add-In)

ControlTemplate Object

Properties Collection

PropertyObject


See Also

Creating Add-Ins

Connecting an Add-in to Visual Basic

Working with Add-in Objects


IndexedValue Property (Add-In)

See Also	Applies To

Returns or sets a value in an indexed list or an array.

Syntax

object.IndexedValue [Index1, [Index2,][ Index3,] [ Index4]][ = value]

The IndexedValue property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

Indexn	A numeric expression specifying index position. IndexedValue accepts up to four indices.  The number of indices accepted by IndexedValue is the value for the same property returned by the NumIndices Property.

value	An expression that evaluates to a type acceptable to the control.

Remarks

IndexedValue is used only if the value of the NumIndices property is greater than zero.  Values in indexed lists, as in the List Property of a ListBox control, are set or returned with a single index.


See Also

NumIndices Property (Add-In)


IndexedValue Property (Add-In) Applies To

Property Object (Add-In)


NumIndices Property (Add-In)

See Also	Applies To

Returns the number of indices on the property returned by the Property object.

Syntax

object.NumIndices

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The value of NumIndices can be anything from 0 to 4.  For normal properties, as in the ForeColor property, NumIndices returns 0.  Conventionally indexed properties, as in the List property of a ListBox control, return 1.  Property arrays might return a 2.


See Also

IndexedValue Property (Add-In)


 NumIndices Property (Add-In) Applies To

Property Object (Add-In)


Make OLE DLL File Command (File Menu)

See Also

Creates an in-process OLE server by combining the form modules, standard modules, class modules, and resource files in a project into a single 32-bit dynamic-link library file (.DLL) (Visual Basic Professional and Enterprise Editions only.)

Developing a DLL is different from developing an EXE.  Because a DLL runs in another application's process, there are programming restrictions you should be aware of.  Before you attempt to build an in-process OLE server, or convert an out-of-process OLE server project to an in-process OLE server, you should be familiar with the information in the following topics:

What is an In-Process OLE Server?

Programming Restrictions for In-Process OLE Servers

Developing In-Process OLE Servers

See also the Professional Edition book Creating OLE Servers.

An in-process OLE server is run when an OLE client creates an object from one of the server's classes.  Like all DLLs, an in-process OLE server cannot be run by itself.

When an OLE client creates an object, the DLL file containing the server is loaded into the OLE client process.  The run-time file VB40032.DLL must be in \WINDOWS\SYSTEM or a directory on the user's path.  You may also need other files, depending on the in-process OLE server's requirements.

This command doesn't affect the project's files.  You can still work with or modify your original files without affecting the DLL file containing the in-process OLE server.

Dialog Box Options

File Name

Type the filename for the DLL, accept the default filename, or browse through the directories and select an existing filename to overwrite.  Unless you specify a filename extension, Visual Basic automatically uses the default filename extension .DLL.

Directories

Select the directory where you want to store the DLL.  You can browse through the directories to select an existing filename to overwrite.

Drives

Select the drive where you want to store the DLL.

OK

Makes an executable version of your application.

Cancel

Closes the dialog box without making a DLL.

Options

Displays the OLE DLL Options dialog box, in which you can set the title and icon for your in-process OLE server, major and minor versioning information, and copyright, trademark, company name, product name, and base address information.

Network

Displays the Connect Network Drive dialog box so that you can connect to a network drive and save your DLL on a remote drive.


See Also

Creating an OLE Server

Developing In-Process OLE Servers

OLE DLL Options Dialog Box

Icon Property

Programming Restrictions for In-Process OLE Servers

Using Externally Creatable Objects

What is an In-Process OLE Server?


Developing In-Process OLE Servers

See Also

An in-process OLE server is a DLL, so it runs in the same process as an OLE client application that uses its objects.  This topic discusses a number of ways in which developing a DLL differs from developing an EXE.

Before you build your first in-process OLE server, you should also be familiar with the information in the following topics:

What is an In-Process OLE Server?

Programming Restrictions for In-Process OLE Servers

See also the Professional Edition book Creating OLE Servers.

Specifying a Base Address

The OLE DLL Options dialog is similar to the Make EXE Options dialog.  The exception is the DLL Base Address option that allows you to enter the base address for an in-process OLE server.  The base address determines where a DLL loads in an OLE client application's address space.

With 32-bit operating systems, the code pages for DLLs are shared between processes that use them, as long as the DLLs can load at the base address.  Therefore, three OLE clients could be using the same DLL, but the code would be loaded into memory only once.  However, if the memory locations a DLL uses in a process space conflict with memory locations used by other DLLs or the executable, then the DLL base address must be "rebased" to another logical memory location.

The memory used by a DLL begins at the initial base address and is the size of the DLL file, rounded up to the next multiple of 64K. If there is any overlap in the memory used by two DLLs, one must be rebased.

Rebasing requires the operating system to dynamically recalculate the logical memory locations where code and data are loaded.  The recalculation slows down the load process, and code that is dynamically relocated generally cannot be shared.

The default DLL base address is a fixed value.  For optimum performance and minimum memory requirements, you can fine-tune your applications using the DLL Base Address option to insure that your in-process OLE servers are not rebased on load.  This is especially important when more than one Visual Basic inprocess OLE server will be loaded because they will all default to the same base address, resulting in guaranteed relocations.

Note   The base address value must be a multiple of 64K.  Executables will normally load at the 4 megabyte logical address.  The region below 4 megabytes is reserved under Windows 95 and regions above two gigabytes are reserved by both Windows 95 and Windows NT.

Debugging In-Process OLE Servers

When you run your in-process OLE server project in the development environment, it can only function as an out-of-process OLE server.  It cannot run in the process of your OLE client test project.

This means that you cannot debug an in-process OLE server when it is running in-process.  You can debug your code by running your server project in one instance of Visual Basic and accessing the properties and methods of its objects from an OLE client test program in a second instance of Visual Basic, just as you would when debugging an out-of-process OLE server.

For more effective debugging, you can run the code for your in-process OLE server with the same restrictions that are placed on the compiled in-process OLE server, by setting the project-level Use OLE DLL Restrictions option on the Tools Options Advanced Tab.

Selecting the Use OLE DLL Restrictions option causes the development environment to generate the same errors that would occur if the in-process OLE server is run in process.  For example, Visual Basic generates a run-time error if a compiled in-process OLE server attempts to show a modeless form.  The same error is generated when the in-process OLE server is run in the development environment with Use OLE DLL Restrictions selected.

Testing Compiled In-Process OLE Servers

Once you have made your in-process OLE server project into a DLL file, you may want to test it using an OLE client program running in the Visual Basic development environment.  When you do this, remember that the in-process OLE server is loaded into Visual Basic's process space.  A fatal error in the DLL file will cause Visual Basic to close abruptly.

An untrapped error in an event procedure in any compiled Visual Basic program is fatal, because there is no procedure higher up in the call list than an event procedure, so there can be no other error handlers.  A fatal error in the in-process OLE server DLL is fatal to the process, that is, to Visual Basic.  Therefore, use caution when testing your in-process OLE server.

Important   When you are designing in-process add-ins for Visual Basic, use error trapping in any event procedure code, including the Initialize and Terminate events of class modules.

Registering In-Process OLE Servers

When you select Make OLE DLL File, Visual Basic registers the newly created in-process OLE server in your computer's Windows registry, just as it would register an out-of-process OLE server.

You can also register an in-process OLE server using REGSVR32.EXE, which is shipped in the \TOOLS\PSS directory.  Visual Basic in-process OLE servers expose the entry point required to support REGSVR32.EXE and the Visual Basic setup toolkit.

Using In-Process OLE Servers with Remote Automation (Enterprise Edition)

An OLE client cannot directly create an object from an in-process OLE server on a remote computer.  However, objects from in-process OLE servers can be used by out-of-process Remote Automation servers.

For example, an OLE client can get a reference to an object provided by an out-of-process OLE server running on a remote computer, and call methods of the object.  Those methods can create and use objects provided by an in-process OLE server on the remote computer.  The in-process OLE server DLL can be loaded into the out-of-process OLE server's process, because the out-of-process OLE server is an executable (.EXE) with its own process.

Methods of the out-of-process OLE server's objects can return references to public objects provided by the in-process OLE server.  An OLE client on another computer can use these references, even though it cannot create the objects directly.

Note   An OLE client can obtain a reference to an object from an out-of-process OLE server on a remote computer, and then call a method of that object to obtain a reference to an object provided by an in-process OLE server on the remote computer.  If the OLE client releases the reference to the first object, and there are no other references to the out-of-process OLE server's objects, the reference to the in-process server's object will not keep the two OLE servers on the remote computer running.  If the out-of-process OLE server unloads, the in-process server must unload with it, and references to its objects become invalid.

Compiling as both In-Process OLE Server and EXE

In-process OLE servers and out-of-process OLE servers use the same version information settings in the project file.  If you create can EXE and an in-process OLE server from the same source, only one set of version information will be saved in the project file.  In addition, there will only be one shared ExeName32 entry in the .VBP file.  For example, if you name your in-process OLE server MYDLL.DLL, when you choose Make EXE File, the default filename will be MYDLL.DLL, not MYDLL.EXE.  Use the Make EXE File or Make OLE DLL File dialogs to appropriately name your executables and in-process OLE servers.

Making an In-Process OLE Server from the Command Line

A new command line switch, /makedll, allows you to compile and build an in-process OLE server from the command line:

vb32[.exe] [[{/run | /r} projfilename] [[{/d compileconst}][{/make | /m | /makedll |/l} projfilename [outputfilename] ] {/cmd argument | /c argument }]

The /makedll switch enables Visual Basic to compile the project and make an in-process OLE server file using the existing settings of the Path, EXEName, and Title properties in the project file.


See Also

Creating an OLE Server

OLE DLL Options Dialog Box

Make OLE DLL File

Programming Restrictions for In-Process OLE Servers

Using Externally Creatable Objects

What is an In-Process OLE Server?


Programming Restrictions for In-Process OLE Servers

See Also

Your in-process OLE server is a DLL running in another application's process.  This topic discusses several important ways in which Visual Basic behaves differently in a DLL, restrictions that apply to Visual Basic code in a DLL, and some programming practices you must follow when you create an in-process OLE server.

Before you create your first in-process OLE server, you should also be familiar with the information in the following topics:

What is an In-Process OLE Server?

Developing In-Process OLE Servers

See also the Professional Edition book Creating OLE Servers.

32-Bit Only

In-process OLE servers can only be developed and used on 32-bit operating systems (Windows 95 or Windows NT).

At Least One Public Class Module is Required

The only way to access an in-process OLE server is by creating an object from a public class.  There must be at least one class module in your project whose Public property is True and whose Instancing property is Createable MultiUse.

Choosing Make OLE DLL File command when there is no public class module in the project generates the error message No public class module detected for this project.

No Modeless Forms

In-process OLE servers cannot display modeless forms.  Showing a form nonmodally generates the run-time error Operation Not Valid in a DLL.

This restriction applies to MDI forms and MDI child forms; that is, forms with the MDIChild, property set to True, because they cannot be shown modally.  A run-time error is generated by an attempt to load an MDI form.

Showing Forms and Message Boxes

When a method in your in-process OLE server displays a form or message box, the OLE client application has a chance to execute code in event procedures, such as Click and Timer events. This should not happen when the developer of the OLE client does not expect it, because re-entrancy problems may occur.

Provide methods that display your modal forms, and name them clearly so that the developer of the client application knows their purpose.

Errors should be returned to the OLE client, either as the return values of methods, or using the Raise method of the Err object.  Do not display errors from your in-process server using modal forms or message boxes, unless you already have a modal form shown.

Sub Main is Required

Since a startup form is by definition modeless, in-process OLE servers must specify a Sub Main (in a standard module).  A compile-time error is generated if Sub Main is not specified.

The code in Sub Main is executed when the in-process OLE server is loaded in response to the OLE client's request to create the first object.  If all object references are released, and the server terminates, Sub Main will be executed again when the OLE client requests that an object be created. The purpose of Sub Main is to initialize global variables and perform other initialization tasks.  Minimal code should be put in an in-process OLE server Sub Main procedure.  No forms or message boxes should be displayed from the Sub Main procedure, and you should not use the DoEvents function in the Sub Main procedure.

DoEvents and Re-entrancy

Use DoEvents cautiously in an in-process OLE server.  DoEvents may allow code in the OLE client, such as a Timer event, to execute.  The OLE client could release all its references to the server while an earlier call is still in progress.

OLE does not serialize calls to methods of an in-process OLE server, so multiple calls to the same method could be in the calls list at the same time.  As with nested DoEvents loops in normal applications, the calls will finish in reverse order. If the method uses Static or global data, results may not be what your user expects.

Using loaded but hidden forms with Timer events in an in-process OLE server can lead to similar situations.

Modal Form Prevents In-Process OLE Server Shutdown

If an in-process OLE server has a modal form visible when the last reference to its objects is released, the visible form will keep the server from unloading.  In effect, this is a 'reference' on behalf of the computer user.

This situation can occur if the OLE client has called a method in the in-process server that shows the modal form, and then in other code [image] for example, a Timer event [image] releases the object reference that was used to call the method.  This is not good OLE client programming practice; it can cause fatal errors when the client application is closing, resulting in failure to execute all termination code.

In-Process OLE Server Shutdown Unloads Hidden Forms

If a form is loaded but not visible when the last reference to an in-process OLE server's objects is released, the form will not keep the OLE server from shutting down.  This is different from the behavior of out-of-process OLE servers.

When an in-process OLE server shuts down, the QueryUnload event procedures of any loaded but hidden forms will not be called.  Unload events will be called, but the Cancel parameter of the Unload events will be ignored.

When all forms have been unloaded, the in-process server shutdown code checks for object references that may have been created in the Unload and Terminate events of forms.  (Objects cannot be created by OLE clients during shutdown.)  If such references have been created, the OLE server cannot complete its termination.

No End Statement

The End statement is not allowed in an in-process OLE server.  It will cause a compile-time error.

No Single Instance Class Modules

A class module in an out-of-process OLE server is marked Createable SingleUse to force a new instance of the server to be loaded each time an instance of the class is created.  Because there is no way to attach a DLL to a process multiple times, this functionality is not possible in an in-process OLE server.

If you set the Instancing property to Createable SingleUse, the following compile-time error will be generated: The instancing property for class 'classname' cannot be set to Createable SingleUse for a DLL.

Avoid Circular Object References

In-process servers should not use circular references.  For example, an object of class A contains a reference to an object of class B and that object of class B contains a reference to the class A object.

Even when the OLE client releases all its references to the circularly referenced objects, Visual Basic will not destroy them and free the memory they are using.  They will continue to take up memory.  This will also cause problems during application termination.

Setting Global Object Variables

Public object variables declared in standard modules in an in-process OLE server should not be set to reference objects supplied by that server.  Doing this will prevent the in-process server from terminating when it should.

Do Not Pass or Return Private Objects

The methods and properties of an in-process OLE server should never return references to an object of a class whose Public property is False, or references to any of the objects in the Visual Basic object library, such as the Printer object, forms, and controls.  Use the Object Browser to view the entire list.

When your in-process OLE server calls the methods of another OLE server, you should never pass references to these objects as parameters of the method.

Private objects were not meant to be used outside your in-process OLE server project.  Passing them to a client application may jeopardize program stability and cause incompatibility with future versions of Visual Basic.

In addition, many of these objects will not keep the in-process server running.  By contrast, even one reference to a public object; that is, an object from a class whose Public property is True, keeps the in-process server from closing.

If the in-process server terminates while the OLE client has a reference to a private object, such as the in-process server's Printer object, code in the OLE client that refers to the object may cause catastrophic program failure.

In-Process OLE Server Interactions with Other OLE Servers

A Visual Basic in-process OLE server relies on the OLE client program to:

Enable repainting of forms while the in-process OLE server is in the middle of a call to another OLE server.

Retry calls to other servers that are temporarily busy.

Inform callers that the in-process server is busy, for example, when it is displaying a modal form; if the client doesn't handle this, the call will fail.

If the OLE client is a Visual Basic compiled executable, it will provide all of the above functionality transparently.

Use Error Trapping in Initialize and Terminate Events

Unlike out-of-process servers, in-process OLE servers are loaded into an application's process space.  For this reason, stability problems with the in-process OLE server can destabilize the entire application.

For example, an untrapped error in the Initialize or Terminate event of an object will cause the abrupt shutdown of an out-of-process OLE server, leaving OLE clients holding invalid object references, but it will not directly cause the OLE clients themselves to fail.

The same error in an in-process OLE server, by contrast, is like an untrapped error in an event procedure of the OLE client; it will cause the abrupt shutdown of the OLE client application.  An untrapped error in an event procedure is always fatal in compiled Visual Basic applications because there is no procedure higher up in the call list than an event procedure, so there can be no other error handlers.

Important   Untrapped errors in any event procedure in an in-process OLE server will cause the client application to shut down abruptly.  Always use error trapping when there is a possibility that errors could be raised in events.

Separate File Numbers

A Visual Basic in-process OLE server does not share file numbers with the OLE client in whose process it is running.  You cannot open a file in the client and pass the file number to the in-process server.  You can use file numbers in the range from 1 to 255 in an in-process OLE server.

DDE is not Supported

In-process OLE servers do not support DDE.

Command$ Returns an Empty String

In an in-process server, Command$ returns an empty string ("").  If the in-process OLE server requires the command-line string from an OLE client, you can create a method the client can call or a property the client can set to pass this information.

App Object

In an in-process OLE server, the App object represents the DLL, not the OLE client process that it is running in.  For example, App.Path returns the directory in which the in-process OLE server is installed.

The following properties of the App object have restrictions or behave differently when used in an in-process OLE server.

Property	In-Process OLE Server Behavior

PrevInstance	Always returns False.

StartMode	Always returns vbSModeAutomation.

Olexxx	Using any of the OLExxx properties, such as OLEServerBusyMsgText, results in run-time error 369 Operation not valid in a DLL.

Screen Object

In an in-process OLE server, the Screen object is affected as follows:

Property	In-Process OLE Server Behavior

ActiveControl	Returns Null if the currently active control is not owned by the in-process OLE server.

ActiveForm	Same as Screen.ActiveControl.

MousePointer	This property is local to the in-process OLE server.  It affects only forms displayed by the in-process OLE server, and cannot be used to detect the state of the OLE client's mouse pointer.

Printer Object

In-process OLE servers maintain a separate printer object.  What the server does to the printer is independent of the client's use of the printer object.  Your code should assume that all printer object use is local to the in-process OLE server.

Forms collection

An in-process OLE server has its own Forms collection.  If the OLE client was written using Visual Basic, the in-process OLE server's Forms collection will be separate from the client application's Forms collection.

Termination of In-Process Server DLLs

There is no termination event that occurs when the in-process OLE server is unloaded.


See Also

Creating an OLE Server

Developing In-Process OLE Servers

Make OLE DLL File

Using Externally Creatable Objects

What is an In-Process OLE Server?


What is an In-Process OLE Server?

See Also

Using Make OLE DLL File, you can create in-process OLE Automation servers.  These files are dynamic link libraries (DLLs) that run in the same process as the programs that use them.

You access the functionality provided by these DLLs using OLE Automation.  Programs created using Visual Basic, Microsoft Access, or any other OLE Automation-enabled programming tool can create objects from the classes in an in-process OLE server, and call the properties and methods of the objects.

For example, an in-process OLE server named Math might have a Calculation class.  A Visual Basic program could use the methods of the Calculation class by keeping a reference to a Calculation object in a variable in a standard module:

' Code in a standard module of the OLE client program.

Public gcalcMain As New Math.Calculation

Because the variable is declared As New, a Calculation object is created the first time the variable is used in code.  If the DLL is not already running, it will be loaded into the OLE client program's process.  Suppose that the Calculation object has a Factor method that takes a Long and returns a Variant array containing its prime factors.  The following code creates the Calculation object and calls the Factor method:

' Code in the OLE client program.

Private Sub Command1_Click()

Dim vntFactors As Variant

Dim vntFactor As Variant

vntFactors = gcalcMain.Factor(4562711)

For Each vntFactor In vntFactors

MsgBox vntFactor

Next

End Sub

Once the Calculation object has been created, it exists until the variable gcalcMain goes out of scope [image] in this case, until the program ends [image] or until gcalcMain is set to Nothing.  The overhead required to create the object is incurred only the first time the variable is referred to.  Alternatively, you could create the Calculation object when the program starts, using the Set statement with the New operator.

Note   You cannot call a Visual Basic in-process OLE server using a Declare statement.

There are restrictions and development considerations particular to building in-process OLE servers.  Before starting an in-process OLE server project, you should also be familiar with the information in the following topics:

Programming Restrictions for In-Process OLE Servers

Developing In-Process OLE Servers

See also the Professional Edition book Creating OLE Servers.

Why Use In-Process OLE Servers?

Calling an in-process OLE server can be significantly faster than making calls to an out-of-process OLE server [image] an executable (EXE) that runs in its own address space [image] because there is no need to transfer parameters and return values between processes.

You can use in-process OLE servers to:

Encapsulate compiled modules of code to be shared among a team of developers.

Create Wizards and Add-Ins for Visual Basic.

Create compiled modules of code that can be called from applications capable of using OLE automation servers, such as Microsoft Access and Microsoft Excel.

Break a large application into an .EXE file containing the user interface and several in-process server components containing the functionality.  The components can then be used in-process by other OLE clients.


See Also

Creating an OLE Server

Developing In-Process OLE Servers

Make OLE DLL File

Programming Restrictions for In-Process OLE Servers

Using Externally Creatable Objects


EXE Options and OLE DLL Options Dialog Boxes

OLE DLL Options Dialog Box

EXE Options Dialog Box


JumptoCCRHelp


action query <definition>
action query

A query that moves or changes data.  Action queries include append, delete, make-table, and update queries.  Delete and update queries change existing data; append and make-table queries move existing data.  In contrast, select queries return data records.  A SQL pass-through query may also be an action query.


action QueryDef <definition>
action QueryDef

A data access object that contains the definition of an action query.  An action QueryDef object is used only with the Execute method, and it defines, moves or changes data instead of returning rows.


aggregate function <definition>
aggregate function

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


alias <definition>
alias

In Visual Basic, an alternate name you give to an external procedure to avoid conflict with a Visual Basic keyword, global variable, constant, or a name not allowed by the standard naming conventions.

In SQL, an alternate name you give to a field or expression in a SELECT statement (Using the AS clause), to make it shorter or more meaningful or to prevent name conflicts when performing SQL queries using expressions that don't return names or in a query that uses a self-join.


append query <definition>
append query

An action query that adds new records to the end of an existing table or query.  Append queries don't return records (rows).


asterisk <definition>
asterisk

A character (*) used as a wildcard in SQL LIKE expressions to accept any string of characters.  For example, the expression LIKE "*town*" accepts any name containing the string "town."

When you create a query or enter an SQL statement, use the asterisk to include all the fields that currently exist in the underlying table or query.  For example, SELECT * FROM MyTable returns all fields (columns) from the table.


attached table <definition>
attached table

A table in another database linked to a Microsoft Jet database.  Data for attached tables remains in the external database where it may be manipulated by other applications.  You can't use the table-type Recordset object with attached tables.


base table <definition>
base table

A table in a Microsoft Jet database.  You can manipulate the structure of a base table using the data access objects or data definition SQL statements, and you can modify data in a base table using Recordset objects or action queries.


bookmark <definition>
bookmark

A system-generated string identifying the current record that is contained in a Recordset object's Bookmark property.  If you assign the Bookmark property 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.  Bookmarks can be shared between cloned Recordset objects.


Boolean <definition>
Boolean

A True/False or yes/no value.  Boolean values are usually stored in Bit fields in a Microsoft Jet database; however, some databases don't support this data type directly.


Byte data type <definition>
Byte data type

A fundamental data type used to hold small positive integer numbers ranging from 0 to 255.


bound control <definition>
bound control

A data-aware control that can provide access to a specific field in a database through a Data control.  A data-aware control can be bound to a Data control through its DataSource and DataField properties.  When a Data control moves from one record to the next, all bound controls connected to the Data control 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.


Cartesian product <definition>
Cartesian product

The result of joining two relational tables, producing all possible ordered combinations of rows from the first table with all rows from the second table.

Generally, a cartesian product results from executing a SQL SELECT statement referencing two or more tables in the FROM clause and not including a WHERE or JOIN clause that indicates how the tables are to be joined.


cascade delete <definition>
cascade delete

For relationships that enforce referential integrity between tables, an option that causes the deletion of a record from the primary table to automatically delete all related records in the related foreign table or tables.

For example, suppose you establish a relationship between a Customers (Primary) table and an Orders (Foreign) table with the cascade delete option enabled.  When a record in the Customers table is deleted, all orders associated with that customer would be also be deleted in the Foreign Orders table.


cascade update <definition>
cascade update

For relationships enforcing referential integrity between tables, an option that causes a change to the primary key in a record in the Primary table to automatically update the foreign key in all related records in the related Foreign table or tables.

For example, suppose you establish a relationship between a Customers (Primary) table and an Orders (Foreign) table with the cascade update option enabled.  When the primary key in a record in the Customers table is changed, all orders associated with that customer would be also be changed in the Foreign Orders table.


cascade <definition>
cascade

The process of  one action triggering another action.  For example, when a cascading update relationship is defined for two (or more) tables, an update to the primary key in the primary table automatically triggers (cascades) changes to the foreign table.


case-sensitive <definition>
case-sensitive

Capable of distinguishing between uppercase and lowercase letters.  A case-sensitive search finds only text that is an exact match of uppercase and lowercase letters.  Such a search would, for instance, treat "ZeroLengthStr" and "zerolengthstr" as different.  Microsoft Jet database operations are not case-sensitive.  However, case sensitivity is a feature of some other database management systems.


column <definition>
column

In a relational database, a column is synonymous with a field in a nonrelational database.  A column defines the data type, size and other attributes of one field of a row (record) of data.  All columns taken as a set define a row (record) in the database.  An individual column contains data related in type and purpose throughout the table; that is, a column's definition doesn't change from row to row.


commit <definition>
commit

To accept a pending transaction.  If you use transaction processing and begin a transaction using data access, none of the changes made in the transaction are written to the database until you commit or accept the transaction.


consistent <definition>
consistent

The state of a multiple-table Recordset object that allows you to only perform updates that result in a consistent view of the data.  For example, in a Recordset that is a join of two or more tables (a one-to-many relationship), a consistent query would not allow you to set the many-side key to a value that isn't in the one-side table.


copy buffer <definition>
copy buffer

A location created by the Microsoft Jet database engine 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 sets the default values; and the Update method saves the data from the copy buffer to the database, replacing the current record or inserting the new record.  Any statement that resets or moves the current record pointer discards the copy buffer.  For example, using the MoveNext method or changing the Index property of a table would discard the contents of the copy buffer.


counter <definition>
counter

A Long data type field in a table where the field Attribute property has the dbAutoIncrement option bit set.  A  counter field is automatically incremented by 1 when a new record is added to the table.  Counter fields are not intended to be updated by the user.


connect string <definition>
connect string

A string used to define the source of data for an external database.  The connect string is usually assigned to the Connect property of a QueryDef object or Data control or as an argument to the OpenDatabase method.


counter field <definition>
counter field

A field that assigns the next consecutive number for each successive record added in the same field.  A counter field always uses the Long data type.


criteria <definition>
criteria

A set of limiting conditions, such as = "Denmark" (meaning equal to Denmark) or > 30000, used in creating a query or filter to show a specific set of records.


crosstab query <definition>
crosstab query

A query that returns data in a spreadsheet type format using fields you specify as row and column headings, and that can return summary data.


Currency data type <definition>
Currency data type

A data type that is useful for calculations involving money or for fixed-point calculations in which accuracy is extremely important.  This data type is used to store numbers with up to 11 digits to the left of the decimal point and 4 digits to the right.  The type-declaration character in Visual Basic is @.  The Currency data type uses discrete values for all amounts so binary round-off isn't a factor when calculating totals.


current database <definition>
current database

The Database object returned by the CurrentDB( ) function.  A reference of DBEngine.Workspaces(0).Databases(0) returns the first database opened.  Not all Microsoft Jet database engine clients support the concept of a "current" database.  This concept isn't supported in Visual Basic version 4.0.


current index <definition>
current index

For an indexed table-type Recordset object, the index most recently set with the Index property.  This index is the basis for ordering records in a table-type Recordset, and is used by the Seek method to locate records.  A Recordset object can have more than one index but can use only one index at a time (although a TableDef object may have several indexes defined on it).  The Microsoft Jet database engine may use more than one index to evaluate a query.


current record <definition>
current record

The record in a Recordset object that you can use to modify or examine data.  Use the Move methods to reposition the current record in a recordset.  Use the Find methods (with a dynaset- or snapshot-type Recordset object) or the Seek method (with a table-type Recordset object) to change the current record position according to specific criteria.

Only one record in a Recordset can be the current record; however, a Recordset may have no current record.  For example, after a dynaset-type Recordset record has been deleted, or when a Recordset has no records, the current record is undefined.  In this case, operations that refer to the current record result in a trappable error.


current transaction <definition>
current transaction

All changes made to a Recordset object after you use the last BeginTrans method and before you use the Rollback or CommitTrans method.


data access object <definition>
data access object

An object that is defined by the Microsoft Jet database engine.  You use data access objects, such as the Database, TableDef, Recordset and QueryDef objects, to represent objects that are used to organize and manipulate data in code.


data page <definition>
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 in a Microsoft Jet database is 2K bytes.


data type (Data Access) <definition>
data type (Data Access)

The attribute of a variable or field that determines what kind of data it can hold.  For example a Field defined with the Text data type is designed to contain text.


database <definition>
database

A set of data related to a particular topic or purpose.  A database contains tables and can also contain queries and indexes as well as table relationships, table and field validation criteria and linkages to external data sources.


database engine <definition>
database engine

That part of the database system that retrieves data from and stores data in user and system databases.


Database object <definition>
Database object

A Database object is a logical representation of a physical database.  A database is a set of data related to a specific topic or purpose.  A database contains tables and can also contain queries and indexes as well as table relationships, table and field validation criteria and linkages to external data sources.


database objects <definition>
database objects

The database objects are Recordset, Field, Index, QueryDef, TableDef, Relation, User, Group, Property and Document.


database management system (DBMS) <definition>
database management system (DBMS)

Software used to organize, analyze, and modify information stored in a database.  For example, the Microsoft SQL Server and the Microsoft Jet database engine are examples of database management systems.


Data control <definition>
Data control

A built-in Visual Basic control used to connect a Visual Basic application with a selected data source.  Bound controls require use of the Data control as a source of data.


data-definition query <definition>
data-definition query

An SQL-specific query that can create, alter, or delete a table, or create or delete an index in a database.


data source <definition>
data source

A named Open DataBase Connectivity (ODBC) resource that specifies the location, driver type and other parameters needed by an ODBC driver to access an ODBC database.  A data source can be any source of database information.


database administration <definition>
database administration

Activities required to preserve the integrity and security of a database, such as maintaining user permissions and backing up, compacting, and repairing the database.


default workspace <definition>
default workspace

The Workspace object that Visual Basic automatically establishes when your application first references any data access object.  This Workspace is referenced by DBEngine.Workspaces(0) or simply Workspaces(0).


delete query <definition>
delete query

An action query that deletes a set of rows that match the criteria you specify.  A delete query doesn't return rows.


Double data type <definition>
Double data type

A fundamental data type that holds double-precision floating-point numbers in IEEE format.  A Double variable is stored as a 64-bit (8-byte) number ranging in value from -1.79769313486232E308 to -4.94065645841247E-324 for negative values, from 4.94065645841247E-324 to 1.797693134862325E308 for positive values, and 0.  The type-declaration character is #.


domain <definition>
domain

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


domain aggregate function <definition>
domain aggregate function

A function used to aggregate data over a certain set of records (the domain).  The domain aggregate 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 <definition>
dynaset

A type of Recordset object that returns a dynamic set of pointers to live database data.  Like a table- or a snapshot-type Recordset, a dynaset returns data in records (rows) and fields (columns).  Unlike a table-type Recordset, a dynaset-type Recordset can be the result of a query that joins two or more tables.  The records in dynaset-type Recordset objects are updatable if their Updatable property is True, the Field being changed is updatable, and the data page containing the current record isn't locked.


Dynaset object <definition>
Dynaset object

A recordset variable that identifies a Dynaset created using the CreateDynaset method.  The Dynaset object is outdated.  It is recommended that you use the dynaset-type Recordset object instead which supports all of the outdated Dynaset properties and methods.


equi-join <definition>
equi-join

A join in which records from two tables are combined and added to the Recordset object only when there are equal values in the joined fields.  In Visual Basic, equi-joins are referred to as inner joins.


expression (Data Access) <definition>
expression (Data Access)

Any combination of operators, constants, literal values, functions, and names of fields, controls, and properties that evaluates to a single value.  You can use expressions as settings for many properties and action arguments, to set criteria or define calculated fields in queries.


external table <definition>
external table

A table in a database outside the open Microsoft Jet database.  An external table may take the form of another file or it may be a table in another relational database.


exclusive <definition>
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 can't be shared by other users.


external database <definition>
external database

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


field <definition>
field

A category of information stored in a table in a database [image] a column of data.  An element of a database table that contains a specific item of information, such as last name.


field data types <definition>
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	Byte

Integer	Integer

Long	Long

Currency	Currency

Single	Single

Double	Double

Date/Time	Date

Text	String

Long Binary	String or Variant; can be up to 1.2 gigabytes.

Memo	String or Variant; can be up to 1.2 gigabytes.

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


field properties <definition>
field properties

Attributes of a field that determine what kind of data it contains.  Size and Type are examples.


filter <definition>
filter

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


foreign key <definition>
foreign key

One or more table fields that refer to the primary key field or fields in another table.  For example, a list of valid part numbers would contain a foreign key to an inventory table containing references to valid part numbers.  Used when establishing referential integrity for a database.


foreign table <definition>
foreign table

A database table used to contain foreign keys.  Generally, you use a foreign table to establish or enforce referential integrity.  The foreign table is usually on the many side of a one-to-many relationship.  An example of a foreign table is a table of state codes or customer orders.


forward scroll <definition>
forward scroll

Move toward the end (EOF) of a Recordset object.


forward-only scrolling snapshot <definition>
forward-only scrolling snapshot

A snapshot-type Recordset object in which records can be searched only from beginning to end; the current record position can't be moved back toward the first record.  Forward-scrolling snapshots are useful for quickly scanning data, such as when you're searching for a particular record.


FROM clause <definition>
FROM clause

The part of an SQL statement that indicates the location of the data to be examined by the query by specifying which database tables are to be included in the search for the desired data.  The location specified by a FROM clause is sometimes called the domain.


group <definition>
group

A collection of user accounts in a Workgroup object, identified by group name and personal identifier (PID).  Permissions assigned to a group apply to all users in the group.


identifier <definition>
identifier

An element of an expression that refers to the value of a field, or property.


index (Data Access) <definition>
index (Data Access)

A dynamic cross-reference of one or more table data fields (columns) that permits faster retrieval of specific records from a table.  As records are added, changed, or deleted, the database management system automatically updates the index to reflect the changes.

When used with a table-type Recordset object, the current index determines the order in which data records are returned to the Recordset.  A table may have several indexes defined for its data.

A data access object that represents an index for a TableDef object.


initialization file <definition>
initialization file

An ASCII text file used to contain parameters for configuring Windows-based applications, the Microsoft Jet database engine or Microsoft Windows itself.  Generally, an initialization file uses the extension .INI and is named after the executable program that uses it.  For example, a program named TESTING.EXE would expect an initialization file called TESTING.INI.


installable ISAM <definition>
installable ISAM

A driver you can specify that allows access to external database formats such as Btrieve, dBASE, Microsoft Excel, and Paradox.  ISAM is an acronym for Indexed Sequential Access Method.  The Microsoft Jet database engine installs (loads) these ISAM drivers when referenced by your application.  The location of these drivers is maintained in the Microsoft Windows registration database.


Integer data type <definition>
Integer data type

A fundamental data type that holds integer numbers.  An Integer variable is stored as a 16-bit (2-byte) number ranging in value from -32,768 to 32,767.  The type-declaration character is % (ANSI character 37).

In Visual Basic, you can use Integers to store Boolean (True/False) values.


inconsistent <definition>
inconsistent

The state of a multiple-table Recordset object that enables you to update all fields (columns).  For example, in a Recordset created by joining two tables in a one-to-many join (as in a Customers and Orders table), you can update Orders.[Customer ID] so that it doesn't match Customers.[Customer ID].


inner join <definition>
inner join

A join in which records from two tables are combined and added to a Recordset only if the values of the joined fields meet a specified condition.  For instance, an equi-join is an inner join in which the values of the joined fields must be equal.


join <definition>
join

A database operation that combines some or all records from two or more tables, such as an equi-join, outer join, or self-join. Generally, a join refers to an association between a field in one table and a field of the same data type in another table.  You create a join with an SQL statement.

When you define a relationship between two tables, you create a join by specifying the primary and foreign table fields.  When you add a table to a query, you need to create a join between appropriate fields in the SQL statement that defines the query.


left outer join <definition>
left outer join

An outer join in which all the records from the left-hand side of the LEFT JOIN operation in the query's SQL statement are added to the Recordset object, even if there are no matching values in the joined field from the right-hand table.  Records from the right-hand table are combined with those from the left-hand table only when there are matching values in the joined fields.  When a left-side record has no match, a row of NULL values is joined on the right side.


left join <definition>
left join

A left outer join includes 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.


locked <definition>
locked

The condition of a data page, Recordset object, or Database object that makes it read-only to all users except the one who is currently entering data in it.


Long Binary <definition>
Long Binary

A data type used to contain binary values up to 1.2 gigabytes in size.


Microsoft Jet database engine <definition>
Microsoft Jet database engine

A database management system that retrieves data from and stores data in user and system databases.  The Jet engine can be thought of as a data manager component with which other data access systems, such as Microsoft Access and Visual Basic, are built.


ODBC (Open Database Connectivity) <definition>
ODBC (Open Database Connectivity)

A standard protocol that permits applications to connect to a variety of external database servers or files.  ODBC drivers used by the Microsoft Jet database engine permit access to Microsoft SQL Server and several other external databases.

The ODBC applications programming interface (API) may also be used to access ODBC drivers and the databases they connect to without using the Jet engine.


one-to-many relationship <definition>
one-to-many relationship

An association between two tables in which:

The primary key value of each record in the primary table corresponds to the value in the matching field or fields of a number of records (or no record) in the related table.

The primary key value of each record in the related table is null or corresponds to the value in the matching field or fields of one and only one record in the primary table.


one-to-one relationship <definition>
one-to-one relationship

An association between two tables in which:

The primary key value of each record in the primary table corresponds to the value in the matching field or fields of no more than one record in the related table.

The primary key value of each record in the related table is null or corresponds to the value in the matching field of one and only one record in the primary table.


optimistic <definition>
optimistic

A type of locking in which the data 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, but is available between the Edit and Update methods.  Optimistic locking is used when accessing ODBC databases or when the LockEdits property of the Recordset object is set to False.


page <definition>
page

A portion of the database in which record data is stored.  Depending on the size of the records, a page may contain more than one record.  In Microsoft Jet databases (.MDB), a page is 2,048 (2K) bytes in length.


parameter (Data Access) <definition>
parameter (Data Access)

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 object to find data about any employee by setting the parameter to a specific name before running the query.


personal identifier (PID) <definition>
personal identifier (PID)

A case-sensitive alphanumeric string 4-20 characters long that the Microsoft Jet database engine uses in combination with the account name to identify a user or group in a Workgroup object.  You provide the PID and the account name when you create a new user or group.


pessimistic <definition>
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.  Pessimistic locking is enabled when the Lockedits property of the Recordset object is set to True.


query <definition>
query

A formalized instruction to a database to either return a set of records or perform a specified action on a set of records as specified in the query.  For example, the following SQL query statement returns records:

SELECT [Company Name] FROM Publishers WHERE State = 'NY'

You can create and run select, action, crosstab, parameter, and SQL-specific queries:


QueryDef object <definition>
QueryDef object

A data access object that contains the SQL statement that describes a query and its properties, such as DateCreated and ODBCTimeout.  Querydef objects with an ODBC Connect property may contain an SQL statement that can only be executed on an external database like Microsoft SQL Server.  This is called an SQL pass-through query.


read-only <definition>
read-only

A type of access to data whereby information can be retrieved but not modified.


record <definition>
record

A set of related data about a person, place, event, or some other item.  Table data is stored in records (rows) in the database.  Each record is composed of a set of related fields (columns) [image] each field defining one attribute of information for the record.  Taken together, a record defines one specific unit of retrievable information in a database.


recordset <definition>
recordset

A logical set of records.  The three types of Recordset objects are dynaset, snapshot, and table.


referential integrity <definition>
referential integrity

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

If you select the Cascade Update Related Fields or Cascade Delete Related Records option for a relationship, the Microsoft Jet database engine allows changes and deletions but changes or deletes related records to ensure that the rules are still enforced.


requery <definition>
requery

To rerun a query to reflect changes to the records, retrieve newly added records, and eliminate deleted records.


right join <definition>
right join

A right outer join includes 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 could 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.


right outer join <definition>
right outer join

An outer join in which all the records from the right-hand side of the RIGHT JOIN operation in the query's SQL statement are added to the Recordset object, even if there are no matching values in the joined field from the left-hand table.  Records from the left-hand table are combined with those from the right-hand table only when there are matching values in the joined fields.


row <definition>
row

A set of related columns or fields used to hold data.  A row is synonymous with a record in the Microsoft Jet database engine.  A table is composed of zero or more rows of data.


security <definition>
security

A set of features used to specify or restrict the access that specified users or user groups have to data and objects in a database.


select query <definition>
select query

A query that asks a question about the data stored in your tables and returns a Recordset object without changing the data.  Once the Recordset data is retrieved, you can examine and make changes to the data in the underlying tables.  In contrast, action queries can make changes to your data, but they don't return data records.


server <definition>
server

The database management system designed to share data with client applications; servers and clients are often connected over a network.  A database server usually contains and manages a central repository of data that remote client applications can retrieve and manipulate.


snapshot <definition>
snapshot

A static copy of a set of records retrieved from the database and copied into memory.  Snapshot-type Recordset objects can be created from a base table, a query, or another recordset.  Snapshots are not updatable.  All SQL pass-through queries return snapshots.


Snapshot object <definition>
Snapshot object

A recordset variable that identifies a Snapshot object created using the CreateSnapshot method.  The Snapshot is outdated.  It is recommended that you use the snapshot-type Recordset instead.


SQL statement/string <definition>
SQL statement/string

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, Recordset objects, and aggregate functions but can also be used to create or modify a database structure.


table <definition>
table

The basic unit of data storage in a relational database.  A table stores data in records (rows) and fields (columns) and is usually about a particular category of things, such as employees or parts. Also called a base table.

A table-type Recordset is a logical representation of a base table in a database.


Table object <definition>
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).  The Table object is outdated.  It is recommended that you use the table-type Recordset instead.


TableDef object <definition>
TableDef object

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.


transaction <definition>
transaction

A series of changes made to a database's data and schema.  Mark the beginning of a transaction with the BeginTrans statement, commit the transaction using the CommitTrans statement, and undo all your changes since BeginTrans using the Rollback statement.

There is an implicit transaction while action queries are running.  If a query doesn't complete for any reason, it is automatically rolled back.

Transactions are optional and can be nested up to five levels.  Transactions increase the speed of data changing operations and enable changes to be reversed easily.

Transactions are global to the referenced database object's Workspace.


update <definition>
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.  The UPDATE clause in an SQL Statement changes data values in one or more records (rows) in a database table.


make table query <definition>
make table query

An action query that creates a new table from the Recordset object of an existing query.


many-only table <definition>
many-only table

A table that doesn't appear as the "one" side of any join in a query.


Memo object <definition>
Memo object

An object you can use to hold the contents of a table field that has a Memo field data type.  Memo objects can contain up to 1.2GB of data.


Memo data type <definition>
Memo data type

A field data type.  Such fields can contain up to 1.2GB of data.


message <definition>
message

A packet of information passed from one application to another.


multiuser database <definition>
multiuser database

A database that permits more than one user to access and modify the same set of data at the same time.  In some cases, the additional "user" may be another instance of your application or another application running on your system that accesses the same data as some other application.


normalize <definition>
normalize

To minimize the duplication of information in a relational database through effective table design.


null (Data Access) <definition>
null (Data Access)

A value that indicates missing or unknown data.  Null values can be entered in fields for which information is unknown and in expressions and queries.  In Visual Basic, the Null keyword indicates a Null value.  Some fields, such as those defined as containing the primary key, can't contain null values.


null field <definition>
null field

A field containing no characters or values.  A null field isn't the same as a zero-length string ("") or a field with a value of 0.  A field is set to null when the content of the field is unknown.  For example, a Date Completed field in a task table would be left null until a task is completed.


Null propagation <definition>
Null propagation

The ability of Null expressions, when used with most operators, to take precedence over other values in expressions.


ODBC driver <definition>
ODBC driver

A dynamic link library (DLL) used to connect a specific Open Database Connectivity data source with another (client) application.


OLE Object data type <definition>
OLE Object data type

A field data type you use for objects created in other applications that can be linked or embedded in a Microsoft Jet database.


outer join <definition>
outer join

A join in which all the records from one table are added to the Recordset object, even if there are no matching values in the joined field from the second table.  Records from the second table are combined with those from the first table only when there are matching values in the joined fields.  Null records are joined when there is no match.


parameter query <definition>
parameter query

A query that requires you to provide one or more criteria values, such as Redmond for City, before the query is run.  A parameter query isn't, strictly speaking, a separate kind of query; rather, it extends the flexibility of other queries.


parse <definition>
parse

To identify the parts of a statement or expression and then validate those parts against the appropriate language rules.


pass-through query <definition>
pass-through query

An SQL-specific query you use to send commands directly to an SQL database server (such as Microsoft SQL Server).  With pass-through queries, you work with the tables on the server instead of attaching them.  Pass-through queries are used to execute SQL queries and system specific commands written using SQL dialects known only to the server.

A pass-through query may or may not return records.  If it does, they are always returned in a snapshot.


permission <definition>
permission

One or more attributes that specify what kind of access a user has to data or objects in a database.  For example, a table or query with Read Data permission permits a user to retrieve but not edit data in the table or query.


primary key <definition>
primary key

One or more fields whose value or values uniquely identify each record in a table.  You can have only one primary key.  An Employees table, for example, could use the social security number for the primary key.


primary table <definition>
primary table

A database table used to contain primary keys.  Generally, a primary key table is used to establish or enforce referential integrity.  The primary table is usually on the one side of a one-to-many relationship with a foreign table.


query parameter data types <definition>
query parameter data types

The set of data types for a field in a parameter query.  The Microsoft Jet database engine has 13 query parameter data types:

Category	Data type

Table fields	Currency, Date/Time, Memo, OLE Object, Text, and Yes/No correspond to the same data types in table fields.

Number	Byte, Single, Double, Integer, and Long Integer correspond to the five Field Size options of the Number data type in table fields.

Generic 	Value is a Generic data type that will accept any type of data.

Binary	You can use the Binary data type in parameter queries directed to attached tables that recognize it.


recordset population <definition>
recordset population

The process of loading Recordset records into memory.

When a dynaset- or snapshot-type Recordset is first opened, it usually contains only one record, even if the query returns additional records.  As your code moves the current record forward (toward EOF) through the Recordset, additional records are fetched and become members of either the keyset (dynaset) or the set of records in memory (snapshot).  This process is called recordset population.  Executing the MoveLast or FindLast methods or setting the  PercentPosition property to 100 completely populates the Recordset.

In Visual Basic version 4.0, when using SQL Passthrough against ODBC data sources, the Recordset isn't fully-populated when first opened (as it was in Visual Basic version 3.0).


secure workgroup <definition>
secure workgroup

A Microsoft Jet database Workgroup object to which users log on with a user name and password and in which access to database objects is restricted according to permissions specified for user accounts and groups.


self-join <definition>
self-join

A join in which records from a table are combined with other records for the same table where there are matching values in the joined fields.  A self-join an be an equi-join or an outer join.  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.


session <definition>
session

A session delineates a sequence of operations performed by the Microsoft Jet database engine.  A session begins when a user logs in and ends when a user logs off.  All operations performed during a session form one transaction scope and are subject to permissions determined by the login user name and password.  Sessions are implemented as Workspace objects by the Jet engine.


Single data type <definition>
Single data type

A fundamental data type that holds single-precision floating-point numbers in IEEE format.  A Single variable is stored as a 32-bit (4-byte) number ranging in value from -3.402823E38 to -1.401298E-45 for negative values, from 1.401298E-45 to 3.402823E38 for positive values, and 0.  The type-declaration character is !.


Structured Query Language (SQL) <definition>
Structured Query Language (SQL)

A language used in querying, updating, and managing relational databases.  SQL can be used to retrieve, sort and filter specific data to be extracted from the database.

You can use SQL SELECT statements anywhere a table name, query name, or field name is accepted.  For example, you can use an SQL statement in place of a table name in the OpenRecordset method.


SQL database <definition>
SQL database

A database that can be accessed through use of Open Database Connectivity (ODBC) data sources.


SQL-specific query <definition>
SQL-specific query

A query that can be created only by writing an SQL statement.  Subqueries and pass-through, union, and data-definition queries are SQL-specific queries.


standard naming conventions <definition>
standard naming conventions

A set of specific rules for naming Microsoft Jet database engine objects.  Names can be up to 64-characters long and can include any combination of letters, numbers, spaces, and special characters except a period (.), an exclamation mark (!), a backquote character (`), and brackets ([ ]).  You also can't use leading spaces or control characters (ASCII values 0 through 31).


String data type <definition>
String data type

A fundamental data type that holds character information.  A String variable can contain approximately 65,535 bytes (64K), is either fixed-length or variable-length, and contains one character per byte.  Fixed-length strings are declared to be a specific length.  Variable-length strings can be any length up to 64K, less a small amount of storage overhead.

The type-declaration character for the String data type is $.


system object <definition>
system object

A database object defined by the Microsoft Jet database engine, such as the table MSysIndexes.


temporary disk <definition>
temporary disk

The disk or directory, identified by the TEMP operating system environment variable, where the Microsoft Jet database engine stores temporary files and result sets.  Also known as temporary drive.  Although the TEMP environment variable may point to a RAM disk, this isn't recommended.


TEMP <definition>
TEMP

A TEMP environment variable is set by your AUTOEXEC.BAT file when you start your system.  Generally, TEMP points to an area on your hard disk used by Microsoft Windows and other programs, like the Microsoft Jet database engine, to store information that doesn't need to be saved after you shut down your system.  For example, the following line in your AUTOEXEC.BAT file points the TEMP environment variable to the D:\TEMPAREA directory:

SET TEMP=D:\TEMPAREA


Text data type <definition>
Text data type

A field data type.  Text fields can contain up to 255 characters or the number of characters specified by the Size property of the Field object, whichever is less.


union query <definition>
union query

A SQL-specific select query that creates a snapshot-type Recordset object containing data from all specified records in two or more tables with any duplicate records removed.  To include the duplicates, add the keyword ALL.

For instance, a union query of the Customers table and the Suppliers table results in a snapshot-type Recordset that contains all suppliers that are also customers.


update query <definition>
update query

An action query that changes a set of records according to criteria you specify.  An update query doesn't return any records.


user account <definition>
user account

An account identified by a user name and personal identifier (PID) that is created to manage access to database objects in a Microsoft Jet database Workgroup object.


validation <definition>
validation

The process of checking whether entered data meets certain conditions or limitations.


validation rule <definition>
validation rule

A rule that sets limits or conditions on what can be entered in one or more fields.  Validation rules can be set for a Field or a TableDef object.  Validation rules are checked when you update a record containing fields requiring validation.  If the rule is violated, a trappable error results.


WHERE clause <definition>
WHERE clause

The part of an SQL statement that specifies which records to retrieve.  The WHERE clause limits the scope of the query and specifies which columns are used to join multiple tables.  When using the Microsoft Jet database engine to perform the query, use the JOIN clause to join multiple tables.


wildcard characters <definition>
wildcard characters

The asterisk (*), question mark (?), number sign (#), exclamation point (!), hyphen (-), and brackets ([ ]) are wildcard characters.  You can use these characters in queries and expressions to include all records, filenames, or other items that begin with specific characters or match a certain pattern.  You can also use wildcard characters and matching characters to further refine a search when using an SQL statement.

Symbol	Example	Usage
*	wh* finds what, white, and why *at finds cat, bat, and what	Like the MS-DOS asterisk (*) wildcard character, this asterisk matches any number of characters.  But unlike MS-DOS, it can be used anywhere in the character string.
?	b?ll finds ball, bell, and bill	Like the MS-DOS ? wildcard character, this symbol matches any single character.
#	1#3 finds 103, 113, 123	Matches any single digit.
[ ]	b[ae]ll finds ball and bell but not bill	Matches any single character within the brackets.
!	b[!ae]ll finds bill and bull but not bell or ball	Matches any character not in the list.
-	b[a-c]d finds bad, bbd, and bcd	Matches any one of a range of characters.
Note   The wildcard characters * (asterisk), ? (question mark), # (number sign), and [ (opening bracket) can match themselves only if enclosed in brackets.


workgroup <definition>
workgroup

A group of users in a multiuser environment who share data and the same system database (typically the SYSTEM.MDW file).


workgroup administrator <definition>
workgroup administrator

A member of the group Admins in a Microsoft Jet database Workgroup object.  A workgroup administrator can always obtain full permissions for any database object created in the Workgroup.


workspace <definition>
workspace

A Workspace object defines a session for a specific user.  When Visual Basic starts, a default Workspace is created with a password of "" and username of "Admin".


Yes/No data type <definition>
Yes/No data type

A field data type that contains a Boolean (True/False or yes/no) value.


zero-length string <definition>
zero-length string

A string containing no characters.  The Len function of a zero-length string returns 0.


standard deviation <definition>
standard deviation

A parameter that indicates the way in which a probability function is centered around its mean and that is equal to the square root of the moment in which the deviation from the mean is squared.  Used to describe sets of values to determine how far the value varies from the arithmetic mean or average.


DDL (Data Definition Language) <definition>
DDL (Data Definition Language)

The language used to describe attributes of a database, especially tables, fields, indexes and storage strategy.


EB data type <definition>
EB data type

Embedded Basic data types, which are defined by Visual Basic itself.


object data type <definition>
object data type

A collective term for objects defined by Visual Basic or by the Microsoft Jet database engine. In this context, an object data type represents objects that are stored in a field in the database.  These can include any of the OLE data types or other long binary fields.


persistent object <definition>
persistent object

An object stored in the database, for example, a database table or QueryDef object.  Dynaset-type or snapshot-type Recordset objects are not considered persistent objects because they are created in memory as needed.


validation properties <definition>
validation properties

Properties used to set conditions on table fields and records.  Validation properties include ValidationRule, Required and AllowZeroLength.


ODBC data source <definition>
ODBC data source

A term used to refer to a database or database server used as a source of data. ODBC data sources are referred to by their Data Source Name.  Data sources can be created using the Windows control panel or the RegisterDatabase method.


reserved word <definition>
reserved word

A word that is part of the Microsoft Jet database engine SQL language.  Reserved words include the names of statements, predefined functions and data types, methods, operators, and objects.  Examples include SELECT, UPDATE, BETWEEN, SET and INSERT.


Data Access Method Summary


Data Access Method Summary

See Also

This reference groups all data-access methods by object or collection and lists them alphabetically.  An asterisk (*) indicates that the method was added for Visual Basic version 4.0.

Grouped by Object or Collection

Column, Columns

Database, Databases

DBCombo

DBEngine

DBGrid

DBList

Document, Documents

Error, Errors

Field, Fields

Group, Groups

Index, Indexes

Parameter, Parameters

Property, Properties

QueryDef, QueryDefs

Recordset, Recordsets

Relation, Relations

TableDef, TableDefs

User, Users

Workspace, Workspaces

Listed Alphabetically

A

Add

AddNew

AppendChunk

Append

B

BeginTrans

C

CancelUpdate

CellText *

CellValue *

Clone

Close

ColContaining *

CommitTrans *

CompactDatabase *

CopyQueryDef

CreateDatabase *

CreateDynaset

CreateField *

CreateGroup *

CreateIndex *

CreateProperty *

CreateQueryDef

CreateRelation *

CreateSnapshot

CreateTableDef

CreateUser *

CreateWorkspace *

D

Delete

DeleteQueryDef

Drag

E

Edit

Execute

ExecuteSQL

F

FieldSize

FillCache *

FindFirst

FindLast

FindNext

FindPrevious

G-H

GetBookmark

GetChunk

GetRows *

I-K

Idle *

L

ListFields

ListIndexes

ListParameters

ListTables

M

MakeReplica *

Move *

MoveFirst

MoveLast

MoveNext

MovePrevious

N

NewPassword *

O-Q

OpenDatabase *

OpenQueryDef

OpenRecordset *

OpenTable

R

Rebind *

Refill *

Refresh

RefreshLink *

RegisterDatabase *

Remove

RepairDatabase *

Requery *

Rollback *

RowBookmark *

RowContaining *

RowTop *

S-T

Scroll *

Seek

SetFocus

ShowWhatsThis *

Synchronize *

U-Z

Update

UpdateControls

UpdateRecord

ZOrder


See Also

Data Access

Events

Objects and Collections

Properties


Data Access Object and Collection Summary


Data Access Object and Collection Summary

See Also

Column, Columns Container, Containers Database, Databases DBCombo  DBEngine DBGrid  DBList  Dynaset Document, Documents Error, Errors Field, Fields Group, Groups Parameter, Parameters	Property, Properties QueryDef, QueryDefs Recordset, Recordsets Relation, Relations RowBuffer SelBookmarks Snapshot Table TableDef, TableDefs User, Users Workspace, Workspaces


See Also

Data Access

Events

Methods

Properties


Data Access Property Summary


Data Access Property Summary

See Also

This reference groups all data-access properties by object or collection and lists them alphabetically.  An asterisk (*) indicates that the property was added for Visual Basic version 4.0.

Grouped by Object or Collection

Column, Columns

Container, Containers

Database, Databases

DBCombo *

DBEngine *

DBGrid

DBList

Document, Documents

Error, Errors

Field, Fields

Group, Groups

Index, Indexes

Parameter, Parameters

Property, Properties

QueryDef, QueryDefs

Recordset, Recordsets

Relation, Relations

RowBuffer

SelBookmarks

Table

TableDef, TableDefs

User, Users

Workspace, Workspaces

Listed Alphabetically

A

AbsolutePosition *

Align

AllowAddNew *

AllowDelete *

AllowRowSizing *

AllowSizing

AllowUpdate *

AllowZeroLength *

AllPermissions *

Appearance *

Attributes *

B

BackColor

BOFAction *

BOF

Bookmark (DBGrid) *

Bookmarkable

Bookmark

BorderStyle

BoundColumn *

BoundText *

C

CachePages *

CacheSize *

CacheStart *

Caption

Clustered *

ColIndex

CollatingOrder *

ColumnCount *

ColumnHeaders *

ColumnName *

Columns *

ConflictTable *

Connect *

Container *

Count *

D

Database

DatabaseName

DataChanged

DataField

DataMode *

DataSource

DataUpdatable *

DateCreated

DefaultPassword *

DefaultUser

DefaultValue *

DefColWidth

Description *

DesignMasterID *

DistinctCount *

DividerStyle

DragIcon

DragMode

E

EditMode

Enabled

EOF

EOFAction

Exclusive

F-G

Fields

Filter

FirstRow

Font

ForeColor

Foreign *

ForeignName *

ForeignTable *

H

HeadBackColor

HeadFont

HeadForeColor

HeadLines

Height

HelpContext

HelpContextID

HelpFile

I-K

IgnoreNulls *

Index (Control Array)

Index

Inherit *

Inherited *

IniPath

IntegralHeight

IsolateODBCTrans

KeepLocal *

L

LastModified

LastUpdated

Left *

ListField  *

Locked *

LockEdits *

LoginTimeout *

LogMessages *

M

MatchedWithList *

MatchEntry

MouseIcon

MousePointer

N

Name *

Negotiate

NoMatch

Number

NumberFormat

O

Object *

ODBCTimeout*

Options

OrdinalPosition *

Owner *

P

Parent

Password *

PercentPosition *

Permissions *

PID *

Primary *

Q

QueryTimeout *

R

ReadOnly

RecordCount

RecordsAffected *

RecordSelectors *

RecordSetType

RecordSet

RecordSource

Replicable *

ReplicaID *

Required *

Restartable *

ReturnsRecords *

RowCount *

RowDividerStyle

RowHeight

RowSource

Row

S

ScrollBars

SelBookmarks *

SelectedItem *

SelEndCol

SelLength

SelStartCol

SelStart

SelText

Size *

Sort

Source

SourceField *

SourceTable *

SourceTableName *

SQL

Style

T

TabIndex

Table *

TabStop

Tag

Text

Transactions

Type *

U

Unique *

Updatable

UserName *

V-Z

V1xNullBehavior *

ValidateOnSet *

ValidationRule *

ValidationText

Value (RowBuffer) *

Value

Version *

VisibleCols

VisibleCount

VisibleItems

VisibleRows

Visible

WhatsThisHelpID *

Width


See Also

Data Access

Events

Methods

Objects and Collections


Data Access Event Summary


Data Access Event Summary

See Also

This reference lists all events alphabetically.  An asterisk (*) indicates that the event was added for Visual Basic version 4.0.

AfterColUpdate *

AfterDelete *

AfterInsert *

AfterUpdate *

BeforeColUpdate *

BeforeDelete *

BeforeInsert *

BeforeUpdate

Change

Click

ColResize *

DblClick

DragDrop

DragOver

Error *

GotFocus

HeadClick*

KeyDown

KeyPress

KeyUp

LostFocus

MouseDown

MouseMove

MouseUp

Reposition

RowColChange Event *

RowLoaded Event *

RowResize Event *

Scroll Event *

SelChange *

UnboundAddData Event *

UnboundDeleteRow Event *

UnboundReadData Event *

UnboundWriteData Event *

Validate


See Also

Data Access

Methods

Objects and Collections

Properties


Bound Data Controls

See Also

Bound data controls enable you to create data access applications that require little or no coding.  To use any of these "data-aware" bound controls, you need to place one or more Data controls on your form.  The Data control establishes a link between the database and any bound controls used to manipulate the data.

The Toolbox displays all the standard Visual Basic controls, including the Data control and bound)controls.  If the bound control you need is not displayed in the Toolbox, use the Tools Custom Controls dialog box to add them to your project.

To write code that references the data access objects (DAO) that the Data control creates, you may need to use the Tools References dialog box to activate the Microsoft DAO 2.5 Object Library.  Some of the controls listed below (*) also have libraries that require activation using this dialog box.

There are ten bound controls in addition to the Data control provided with Visual Basic:

 Data *  Use to provide access to data in databases through bound controls on your form.  Creates and manages Database and Recordset objects for use by bound controls.  Required for use with all other bound controls.

 DBCombo *  Use to draw a bound combination list box and text box.  The list can be filled automatically from a Data control.  The user can either choose an item from the list or enter a value in the text box.  Can be used to provide read/write-access to a specified text data field selected from the list.

 DBList *  Use to display a Data control-generated list of items from which the user can choose one.  The list can be filled automatically from a Data control and provide read/write access to a specified text data field selected from the list.

 DBGrid *  Use to draw a bound grid composed of multiple records.  The grid can be filled automatically from a Data control.  The user can either choose an item from the grid, or enter a value in the new record.  Can be used to provide read/write-access to a Recordset.

 Label  Use for text that you don't want the user to change, such as a caption under a graphic.  Can be used to provide display-only access to a specified text data field.

 TextBox  Use to hold text that the user can either enter or change.  Can be used to provide read/write-access to a specified text data field.

 CheckBox  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.  Can be used to provide read/write-access to a specified boolean or bit data field.

 ComboBox  Use to draw a combination list box and text box.  The list is filled with the AddItem method. The user can either choose an item from the list or enter a value in the text box.  Can be used to provide read/write-access to a specified text data field selected from the list.  See DBCombo control

 ListBox  Use to display a list of items from which the user can choose one.  The list is filled with the AddItem method. The user can choose an item from the list.  Can be used to provide read/write access to a specified text data field selected from the list.  See DBList control

 PictureBox  Use to display a graphical image from a bitmap, icon, or metafile on your form.  Can be used to provide read/write-access to a specified image/binary data field.

 Image  Use to display a graphical image from a bitmap, icon, or metafile on your form.  Images displayed in an Image control are only decorative and use fewer resources than a PictureBox.  Can be used to provide read/write-access to a specified image/binary data field.


See Also

Activating Data Access Objects

Binding a Control to a Data Control

Data Access Overview

Data Control

Recordset object, Recordsets Collection

Using Data Access


Microsoft Jet Database Engine 2.5/3.0

See Also

The following diagram illustrates the Jet database engine version 2.5/3.0 Data Access Object model.  Click on a specific object in the diagram to get more information.


See Also

Activating Data Access Objects

Binding a Control to a Data Control

Data Access Overview

Database Object, Databases Collection

Data Control

Microsoft Jet Database Engine 1.1

Recordset object, Recordsets Collection

Using Data Access


Microsoft Jet Database Engine 1.1

See Also

The following diagram illustrates the Jet database engine version 1.1 Data Access Object model.  Click on a specific object in the diagram to get more information.


See Also

Activating Data Access Objects

Binding a Control to a Data Control

Data Access Overview

Database Object, Databases Collection

Data Control

Microsoft Jet Database Engine 2.5

Recordset object, Recordsets Collection

Using Data Access


Using Data Access


Using Data Access

See Also

The following topics can provide additional detailed information on specific subjects.

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing Databases on CD-ROM

Accessing External Databases

Activating Data Access Objects

Activating Security

Binding a Control to a Data Control

Building SQL Statements in Code

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings

Changing the System Database

Choosing a Data Control Recordset Type

Choosing a Field Data Type

Connecting to ODBC Databases

Converting a Database Into a Replicable Form

Creating A Database

Creating Parameter Queries

Customizing Data Access .INI Settings

Customizing Windows Registry Settings for Data Access Objects

Examples of Converting Code to Version 2.5

Implementing the DBList and DBCombo Controls

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Locking Behavior in Multiuser Applications

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

Managing Connections to ODBC Data Sources

Moving Design-Master Status to Another Replica

Obsolete Features in DAO

Opening a Database with the Data Control

Populating Recordsets

Positioning the Current Record Pointer

Querying a Database

Resolving Synchronization Conflicts

Retrieving Data Using SQL

Selecting a Recordset Type for Data Access Objects

Specifying the OLE Link Format

Synchronizing Replicas

Using Bookmarks With the Microsoft Jet Version 2.5/3.0 Engine

Using Counter Fields

Using Microsoft Jet Version 3.0 and 2.5

Using Named Arguments

Using Parameter Queries with the Data Control

Using SQL PassThrough

Using the DBGrid Control

Using the MSysConf Table with SQL Databases


See Also

Data Access


Data Access

Concepts

Data Access Overview

Data Access Objects and Collections

Using Data Access

Controls

Data Control

Bound Data Controls

Object Models

Microsoft Jet Database Engine 2.5/3.0

Microsoft Jet Database Engine 1.1

Reference

Constants

Events

Methods

Objects and Collections

Properties

Trappable Data Access Errors


Data Access Objects and Collections

See Also

Data access objects and collections provide a framework for using code to create and manipulate components of your database system.  Objects and collections have properties that describe the characteristics of database components and methods that you use to manipulate them.  Using the containment framework, you create relationships among objects and collections, and these relationships represent the logical structure of your database system.

Objects and collections provide different types of containment relationships:  Objects contain zero or more collections, all of different types; and collections contain zero or more objects, all of the same type.  Although objects and collections are similar entities, the distinction differentiates the two types of relationships.

Notes

If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available.  To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.

If no SYSTEM.MDW file is available to the Microsoft Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.

In the following table, the type of collection in the first column contains the type of object in the second column.  The third column describes what each type of object represents.

Collection	Object	Description

Columns	Column	Used to store column information for the DBGrid control.

Containers	Container	Storage for information about a predefined object type.

Databases	Database	An open database.

None	DBEngine	The Microsoft Jet database engine.

Documents	Document	Information about a saved, predefined object.

Errors	Error	Information about any errors associated with this object.

Fields	Field	A column that is part of a table, query, index, relation, or recordset.

Groups	Group	A group of user accounts.

Indexes	Index	Predefined ordering and uniqueness of values in a table.

Parameters	Parameter	A parameter for a parameter query.

Properties	Property	A built-in or user-defined property.

QueryDefs	QueryDef	A saved query definition.

Recordsets	Recordset	The records in a base table  or query.

Relations	Relation	A relationship between fields in tables and queries.

SelBookmarks	Bookmark	A set of selected rows in the DBGrid object.

TableDefs	TableDef	A saved table definition.

Users	User	A user account.

Workspaces	Workspace	A session of the Jet database engine.


See Also

Activating Data Access Objects

Activating Security


Field Object, Fields Collection

See Also	Example	Properties	Methods 	Summary

A Field object represents a column of data with a common data type and a common set of properties.

A Fields collection contains all stored Field objects of an Index, QueryDef, Recordset, Relation, or TableDef object.

Remarks

The Fields collections of Index, QueryDef, Relation, and TableDef objects contain the specifications for the fields those objects represent.  The Fields collection of a Recordset object represents the Field objects in a row of data, or record.  You use the Field objects in a Recordset to read and to set values for the fields in the current record of the Recordset.

You manipulate a field using a Field object and its methods and properties.  For example, you can:

Get or set the presentation order of the Field object in a Fields collection using the OrdinalPosition property.

Read the SourceField and SourceTable property settings to determine the original source of the data.

Read or set the ForeignName property setting for a field in a Relation object.

Read or set the AllowZeroLength, DefaultValue, Required, ValidateOnSet, ValidationRule, or ValidationText property setting to find or specify validation conditions.

Read or set the Value property of a Recordset.

Use the AppendChunk, FieldSize, and GetChunk methods to get or set a value in a OLE Object or Memo field of a Recordset.

You can refer to the Value property of a Field object that you create and append to a Fields collection by:

Its Name property setting using this syntax:

Fields("name")

-Or-

Fields!name

Note   Fields that have names with embedded spaces must be delimited with brackets as in [Part Number] or enclosed in single (' ') or double (" ") quotation marks, as in 'Part Number' or "Part Number".

For example:

Fields![long name]

-Or-

Fields("long name")

Its position in the Fields collection using this syntax:

Fields(0)

To create a new Field object in an Index, TableDef, or Relation object, use the CreateField method.

When the Field object is accessed as part of a Recordset object, data from the current record is visible in the Field object's Value property.  To manipulate data in the Recordset, you won't usually reference the Fields collection directly, but instead use syntax as shown below that references the Fields collection as the default collection of the Recordset.  For example, to manipulate data from a Recordset, you use the following syntax that indirectly references the Value property of Field object in the Fields collection of the Recordset:

Dim Rs As Recordset, Db As Database

Set Db = Workspaces(0).OpenDatabase("MYDB.MDB")

Set Rs = Db.OpenRecordset("Select [Part Name], Size,  " _

& "[Part Type], [Part Age] AS Age FROM MyTable")

'Return the Part Name field in the Recordset.

Debug.Print Rs.Fields(0).Value

' Or, use indirect coding.

Debug.Print Rs(0)	' Return the value of the Part Name field.

Debug.Print Rs("Part Name")	' Also return the Part Name field value.

Debug.Print Rs![Part Type]	' Return the Part Type field.

Debug.Print Rs!Age	' Return the Part Age field aliased as Age.


See Also

Activating Data Access Objects

AppendChunk Method

CreateField Method

Delete Method

Fields Property

FieldSize Method

GetChunk Method

Index Object, Indexes Collection

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Relation Object, Relations Collection

TableDef Object, TableDefs Collection


Field Object, Fields Collection Example

This example creates a TableDef object and a Field object, appends the Field to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the current database.  The example enumerates all the fields in the new TableDef object and all the properties of the new Field.  See the methods and properties listed in the Field summary topic for additional examples.

Function EnumerateField () As Integer

Dim MyDatabase As Database

Dim MyTableDef As TableDef

Dim MyField As Field

Dim I As Integer

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTableDef = MyDatabase.CreateTableDef("MyTable")

Set MyField = MyTableDef.CreateField("MyField", dbDate)

MyTableDef.Fields.Append MyField

MyDatabase.TableDefs.Append MyTableDef

' Get database name.

Debug.Print

Debug.Print "Database Name: "; MyDatabase.Name

Debug.Print

' Enumerate all fields in MyTableDef.

Debug.Print "TableDefs: Name; Fields: Name"

For I = 0 To MyTableDef.Fields.Count - 1

Debug.Print "  "; MyTableDef.Name;

Debug.Print "; "; MyTableDef.Fields(I).Name

Next I

Debug.Print

' Enumerate built-in properties of MyField.

Debug.Print "MyField.Name: "; MyField.Name

Debug.Print "MyField.AllowZeroLength: "; MyField.AllowZeroLength

Debug.Print "MyField.Attributes: "; MyField.Attributes

Debug.Print "MyField.CollatingOrder: "; MyField.CollatingOrder

Debug.Print "MyField.DefaultValue: "; MyField.DefaultValue

Debug.Print "MyField.OrdinalPosition: "; MyField.OrdinalPosition

Debug.Print "MyField.Required: "; MyField.Required

Debug.Print "MyField.Size: "; MyField.Size

Debug.Print "MyField.SourceField: "; MyField.SourceField

Debug.Print "MyField.SourceTable: "; MyField.SourceTable

Debug.Print "MyField.Type: "; MyField.Type

Debug.Print "MyField.ValidateOnSet: "; MyField.ValidateOnSet

Debug.Print "MyField.ValidationRule: "; MyField.ValidationRule

Debug.Print "MyField.ValidationText: "; MyField.ValidationText

EnumerateField = True

End Function


Field Object Properties

Legend

AllowZeroLength

Attributes

CollatingOrder

Count

DataUpdatable

DefaultValue

ForeignName

Name

OrdinalPosition

Required

Size

SourceField

SourceTable

Type

ValidateOnSet

ValidationRule

ValidationText

Value

A Field object may have additional properties that can only be set and manipulated using Microsoft Access.


Field Object, Fields Collection Methods

Legend

Append

AppendChunk

CreateProperty

Delete

FieldSize

GetChunk

Refresh


Field Object, Fields Collection Summary

Field Object

A Field object contains these collections, methods, and properties.

Collection

Properties

Methods

AppendChunk

CreateProperty

FieldSize

GetChunk

Properties

AllowZeroLength	Name	Type

Attributes	OrdinalPosition	ValidateOnSet

CollatingOrder	Required	ValidationRule

DataUpdatable	Size	ValidationText

DefaultValue	SourceField	Value

ForeignName	SourceTable

Fields Collection

A Fields collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Table Object

See Also	Properties	Methods	Summary

A Table object is a read-write data access object.  Generally, a Table object is a logical representation of a physical table in a database that contains information about a particular subject.

Note   The Table object is included for compatibility with earlier versions.  It's recommended that you use the table-type Recordset object and its associated methods and properties instead.  The Table object created with the OpenTable method is different from the table-type Recordset.  Although both have similar properties and methods, the table-type Recordset supports significant additional functionality.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.

Remarks

Like all recordsets, tables have records (rows) and fields (columns).  Unlike other types of Recordset objects, a Table object can only refer to one base table.

You can order the data returned by a Table object by setting the object's Index property to a valid index.  Table indexes are created and managed by the Microsoft Jet database engine when you use Microsoft Access or write a procedure to append a valid Index object to the Indexes collection of the TableDefs collection.  See Index Object, Indexes Collection for more information.  If an index isn't specified, the order in which records are returned can't be determined.

To create a Table object, use the OpenTable method on a Database object.

Table objects can be created with Jet database base tables, but not with ODBC or attached tables.  These recordsets can be used with ISAM databases (like FoxPro, dBASE, Paradox, or Btrieve) when the database is opened directly.  For example, to open a Table object using a dBASE IV table:

Dim Db As Database

Dim Tb As Table

Set Db = Workspaces(0).OpenDatabase("C:\DBASE", False, False,"DBASE IV")

Set Tb = Db.OpenTable("PARTS.DBF")


See Also

Activating Data Access Objects

Converting Code to the Jet Database Engine Version 2.5/3.0

Database Object

Dynaset Object

Dynaset-Type Recordset

Field Object, Fields Collection

Index Object, Indexes Collection

Name Property

OpenRecordset Method

OpenTable Method

Recordset Object, Recordsets Collection

Snapshot Object

Snapshot-Type Recordset

Table-Type Recordset

TableDef Object, TableDefs Collection


Table Object Properties

Legend

BOF

Bookmark

Bookmarkable

DateCreated

EOF

Index

LastUpdated

LockEdits

NoMatch

RecordCount

Transactions

Updatable


Table Object Methods

Legend

AddNew

Clone

Close

CreateDynaset

CreateSnapshot

Delete

Edit

ListIndexes

MoveFirst

MoveLast

MoveNext

MovePrevious

Seek

Update


Table Object Summary

The Table object contains these methods and properties.

Methods

AddNew	ListIndexes

Clone	MoveFirst

Close	MoveLast

CreateDynaset	MoveNext

CreateSnapshot	MovePrevious

Delete	Seek

Edit	Update

Properties

BOF	LastUpdated

Bookmark	LockEdits

Bookmarkable	NoMatch

DateCreated	RecordCount

EOF	Transactions

Index	Updatable


Index Object, Indexes Collection

See Also	Example	Properties	Methods	Summary

Index objects specify the order of records accessed from database tables and whether or not duplicate records are accepted.  Index objects also provide efficient access to data.  For external databases, Index objects describe the indexes established for external tables.

An Indexes collection contains stored Index objects of a TableDef object.

Remarks

The Microsoft Jet database engine maintains all base table indexes automatically.  Once created, you must use the CompactDatabase method periodically.  Indexes are updated whenever you add, change, or delete records from the base table.

The Jet engine uses indexes when it joins tables and creates recordsets.  Indexes determine the order of records returned by Table objects and table-type Recordsets, but they don't determine the order in which records are stored in the base table or the order of records returned from any other type of recordset.

When accessing a table-type Recordset or Table object, you specify the order of records using the object's Index property.  Set this property to the Name property setting of an existing Index object in the Indexes collection.  This collection is contained by the TableDef object that underlies the Recordset object that you're populating.  For example, to order your table-type Recordset by the Publisher's ZIP Code index, you could use the following code:

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set MyRs = Db.OpenRecordset("Publishers", dbOpenTable)

MyRs.Index = "ZIP_INDEX"

Tip   You don't have to create indexes for a table, but in large, unindexed tables, accessing a specific record or processing joins can take a long time.  Conversely, having too many indexes can slow down updates to the database as each of the table indexes is amended.

The Attributes property of each Field object in the index determines the order of records returned and consequently determines the access techniques to use for that index.

Each Field object in the Fields collection of an Index object is a component of the index.  You define a new Index by setting its properties before you append it to a collection, which makes the Index available for subsequent use.

Note   You can use the Append or Delete method on an Indexes collection or modify the Name property setting of an existing Index only if the Updatable property setting of the containing TableDef object is True.

Using an Index object and its properties, you can:

Use the Required property to determine whether the Field objects in the index require non-Null values, and you can use the IgnoreNulls property to determine whether the Null values have index entries.

Use the Primary and Unique properties to determine the ordering and uniqueness of the Index.

When you set a primary key for a table, the Jet database engine automatically defines it as the primary index.  A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order.  Because the primary index field must be unique, the Jet engine automatically sets the Unique property of the primary Index object to True.  If the primary index consists of more than one field, each field can contain duplicate values, but the combination of values from all the indexed fields must be unique.  A primary index consists of a key for the table and is always made up of the same fields as the primary key.

If you attempt to create an Index object and your data doesn't comply with the attributes specified for the index, such as nonunique or Null values in an indexed field, a trappable error results when you attempt to use the Append method on the new index.

When you create a relationship that enforces referential integrity, the Jet database engine automatically creates an index with the Foreign property set as the foreign key in the referencing table.  Once you've established a table relationship, the Jet engine prevents additions or changes to the database that violate that relationship.  If you set the Attributes property of the Relation object to allow cascade update and cascade delete operations, the Jet engine updates or deletes records in related tables automatically.

To create a new Index object

1.	Use the CreateIndex method on the TableDef object.

2.	Use the CreateField method on the Index object to create a Field object for each field (column) to be included in the Index.

3.	Set Index properties as needed.

4.	Append the Field object to the Fields collection.

5.	Append the Index to the Indexes collection.

For example:

' Create new Index object.

Set MyIndex = MyTableDef.CreateIndex("Another")

Set MyField = MyIndex.CreateField("LastName")

MyIndex.Primary = True

MyIndex.Required = True

MyIndex.Fields.Append MyField

' Save Index definition by appending it to Indexes collection.

MyTableDef.Indexes.Append MyIndex

Important   Make sure your data complies with the attributes of your new index.  If your index requires unique values, make sure that there are no duplicates in existing data records or the Jet engine can't create the index, resulting in a trappable error.

Note   The Clustered property is ignored for databases that use the Jet engine, which doesn't support clustered indexes.


See Also

Activating Data Access Objects

Attributes Property

CompactDatabase Method

CreateIndex Method

Field Object, Fields Collection

Index Property

OrdinalPosition Property

Primary Property

Property Object, Properties Collection

Recordset Object, Recordsets Collection

Relation Object, Relations Collection

Table Object

TableDef Object, TableDefs Collection


Index Object, Indexes Collection Example

This example creates a new TableDef object and two new Field objects, appends the Field objects to the Fields collection in the new TableDef, and appends the TableDef to the TableDefs collection in the database.  Then it creates a new primary Index object, includes the two Field objects in it, and appends the Index to the Indexes collection of the TableDef.  Finally, the example enumerates the Index objects in the current database.  See the methods and properties listed in the Index summary topic for additional examples.

Function EnumerateIndex () As Integer

Dim  MyDatabase As Database

Dim MyTableDef As TableDef

Dim MyField As Field, MyIndex As Index

Dim I As Integer

' Get workspace and database.

Set MyDatabase = Workspaces(0).OpenDatabase("MyDB.MDB")	' Create table with two fields.

Set MyTableDef = MyDatabase.CreateTableDef("MyTable")

Set MyField = MyTableDef.CreateField("Field1", dbLong)

MyField.Required = True	' No Null values allowed.

MyTableDef.Fields.Append MyField

Set MyField = MyTableDef.CreateField("Field2", dbLong)

MyField.Required = True	' No Null values allowed.

MyTableDef.Fields.Append MyField

MyDatabase.TableDefs.Append MyTableDef

' Create primary index for those two fields.

Set MyIndex = MyTableDef.CreateIndex("MyIndex")

MyIndex.Primary = True

MyIndex.Unique = True

Set MyField = MyTableDef.CreateField("Field1")

MyIndex.Fields.Append MyField

Set MyField = MyTableDef.CreateField("Field2")

MyIndex.Fields.Append MyField

MyTableDef.Indexes.Append MyIndex

' Enumerate index and its fields.

Debug.Print "Index: "; MyIndex.Name

Debug.Print "  Required: "; MyIndex.Required

Debug.Print "  IgnoreNulls: "; MyIndex.IgnoreNulls

Debug.Print "  Primary: "; MyIndex.Primary

Debug.Print "  Clustered: "; MyIndex.Clustered

Debug.Print "  Unique: "; MyIndex.Unique

Debug Print "  Foreign: "; MyIndex.Foreign

Debug.Print

Debug.Print "Fields in Index: ";

For I = 0 To MyIndex.Fields.Count - 1

Debug.Print " "; MyIndex.Fields(I).Name;

Next I

Debug.Print

EnumerateIndex = True

End Function

This example opens a table-type Recordset and selects an index for the Recordset.  By setting an index, the Microsoft Jet database engine returns records in the order specified by the index.  Without an index, table-type Recordset objects return records from the database table in no particular order.

Dim Db As Database

Dim MyTable as Recordset, MyIndex As Index

Dim I As Integer

' Get workspace and database.

Set Db = Workspaces(0).OpenDatabase("MyDB.MDB")

Set MyTable = Db.OpenRecordset("Titles", dbOpenTable)

MyTable.Index = "MyIndex"

.

.

.


Index Object, Indexes Collection Properties

Legend

Clustered

Count

Foreign

IgnoreNulls

Name

Primary

Required

Unique


Index Object, Indexes Collection Methods

Legend

Append

CreateField

CreateProperty

Delete

Refresh


Index Object, Indexes Collection Summary

Index Object

The Index object contains these collections, methods, and properties.

Collections

Fields (default)

Properties

Methods

CreateField

CreateProperty

Properties

Clustered	Primary

Foreign	Unique

IgnoreNulls	Required

Name

Indexes Collection

The Indexes collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Container Object, Containers Collection

See Also	Example	Properties	Summary

A Container object holds information describing the objects which are grouped into that container.  A Containers collection contains all of the Container objects that are defined in a database.

Remarks

Each Database object has a Containers collection consisting of built-in Container objects.  Some of these Container objects are defined by the Microsoft Jet database engine while others may be defined by other applications.  The following table lists the name of each Container object defined by the Microsoft Jet database engine and what type of information it contains.

Container name	Contains information about

Databases	Containing database

Tables	Saved tables and queries

Relationships	Saved relationships

Note   Don't confuse the particular types of Container objects listed in the preceding table with the collection types of the same name.

The Databases type of Container object refers to all saved objects of the specified type, but the Databases collection refers only to open objects of the specified type.

Each Container object has a Documents collection that contains a Document object for each instance of the type of object it describes.  You typically use a Container object with one of the Document objects in the Documents collection, so you can consider a Container object to be an intermediate link to the information that the Document object contains.

Because Container objects are built-in, you can't create new Container objects or delete existing ones.  Using the properties of an existing Container object, you can:

Determine the predefined names an object has by checking its Name property setting.

Determine or specify the owner of the Container object by checking or setting its Owner property.  To set the Owner property, you must have write permission for the Container object, and you must set the property to the name of an existing User or Group object.

Set access permissions for the Container object using the Permissions and UserName properties; any Document object created in the Documents collection of a Container object inherits these access permission settings.

You can refer to a Container object in a collection by its ordinal number or by its Name property setting using this syntax:

Containers("name")

Note   If no SYSTEM.MDW file is available to the Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.


See Also

Activating Data Access Objects

Activating Security

Document Object, Documents Collection

Group Object, Groups Collection

Property Object, Properties Collection

User Object, Users Collection


Container Object, Containers Collection and Document Object, Documents Collection Example

This example enumerates the properties of all the Container and Document objects in the current database.  See the properties listed in the Container and Document summary topics for additional examples.

Function EnumerateDocuments () As Integer

Dim MyDatabase As Database

Dim MyContainer As Container, MyDocument As Document

Dim I As Integer, J As Integer

Set MyDatabase = Workspaces(0).OpenDatabase("MyDB.MDB")

For J = 0 To MyDatabase.Containers.Count - 1

Set MyContainer = MyDatabase.Containers(J)

Debug.Print ">> Container: "; MyContainer.Name;

Debug.Print "  Owner: "; MyContainer.Owner

Debug.Print "  UserName: "; MyContainer.UserName;

Debug.Print "  Permissions: "; MyContainer.Permissions

Debug.Print

For I = 0 To MyContainer.Documents.Count - 1

Set MyDocument = MyContainer.Documents(I)

Debug.Print " > Document: "; MyDocument.Name;

Debug.Print "  Owner: "; MyDocument.Owner;

Debug.Print "  Container: "; MyDocument.Container

Debug.Print "  UserName: "; MyDocument.UserName;

Debug.Print "  Permissions: "; MyDocument.Permissions

Debug.Print "  DateCreated: "; MyDocument.DateCreated;

Debug.Print "  LastUpdated: "; MyDocument.LastUpdated

Debug.Print

Next I

Next J

EnumerateDocuments = True

End Function


Container Object, Containers Collection Properties

Legend

AllPermissions Property

Count

Inherit Property

Name

Owner

Permissions

UserName


Container Object, Containers Collection Summary

Container Object

The Container object contains no methods and these collections and properties.

Collections

Documents

Properties

Properties

Name

Owner

Permissions

UserName

Containers Collection

The Containers collection contains this method and this property.

Method

Refresh

Property

Count


Database Object, Databases Collection

See Also	Example	Properties	Methods	Summary

A Database object represents an open database.

A Databases collection contains all open Database objects opened or created in a Workspace object of the Microsoft Jet database engine.

Remarks

You manipulate an open database using a Database object and its methods and properties.  You can examine the collections in a Database object to learn about its tables, queries, and relationships.  You can also use its collections to modify or create tables, queries, recordsets, and relationships.  For example, you can:

Use the Execute method to run an action QueryDef or pass an SQL string to an ODBC database.

Use the OpenRecordset method to create a new Recordset object directly from the Database object.

Use the Close method to close an open database.

Note   If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available. To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.

You use the CreateDatabase method to create a new, persistent Database and append it to the Databases collection, thereby saving it on disk.  Once you create a new database, you must create new tables to hold your data.  You can also create new indexes and table relationships, attach existing external tables, or establish a protection scheme using permissions, groups, and users.

To open an existing Database object, use the OpenDatabase method, which appends it to the Databases collection.  OpenDatabase applies to the Workspace object.  You can use OpenDatabase on the default Workspace(0) object, or a different opened Workspace object.

When you use one of the transaction methods (BeginTrans, CommitTrans, or Rollback) on the Database, these transactions apply to all databases opened on the Workspace from which the Database object was opened.  If you want to use independent transactions, you must open an additional Workspace object, and open another Database object using it.  For example, to create two independent Database objects:

Dim Db1 As Database, DB2 As Database, Ws As Workspace, WS2 As Workspace

Dim MyUserName As String

Set Ws = Workspaces(0)	' Use the default Workspace.

Set Db1 = Ws.OpenDatabase("MYDB.MDB")

' Get UserName of default Workspace.

MyUserName = Ws.UserName

' Create new Workspace.

Set WS2 = DBEngine.CreateWorkspace("Special", MyUserName, "SpecialPW")

Set Db2 = WS2.OpenDatabase("MYDB.MDB")

You can also use the outdated OpenDatabase function instead of the OpenDatabase method to create a Database object.  In this case, the default Workspaces(0) is always used.

It isn't necessary to specify the DBEngine object when using the OpenDatabase method.  It's only when you need to open a Database object in a separate transaction context that a specific Workspace object needs to be referenced.  For example, the following statements are equivalent:

Set Db = DBEngine.Workspaces(0).OpenDatabase("MYDB.MDB")

Set Db = Workspaces(0).OpenDatabase("MYDB.MDB")

Set Db = OpenDatabase("MYDB.MDB")

Opening a database that has attached tables doesn't automatically establish links to the specified external files or external ODBC databases until the table's TableDef or Field objects are referenced or a Recordset object is opened on it.  If links to these tables can't be established, a trappable error occurs.  You may also need permission to access the database, or the database may already be open for exclusive use by another user.  In these cases, trappable errors occur.

You can also open an external database directly instead of opening a Jet database that has links to its tables.  The Jet database engine supports a number of external databases, such as FoxPro, dBASE, Paradox, etc., as well as ODBC databases such as Microsoft SQL Server.  See the OpenDatabase method for more information.  For example, to open a FoxPro database, you could use the following code:

Dim Db As Database

Set Db = Workspaces(0).OpenDatabase("C:\FoxFiles", _

False,False,"FoxPro 2.5")

After you open an external database, you can examine the Connect property of the Database object to determine the parameters used to access the database.  When an external ODBC database is opened directly, you can't use table-type Recordset objects.

Each time you open an external ODBC database directly, you establish a connection to the external database server.  The Jet engine also executes additional queries on the database to determine the structure of accessed tables.  Therefore, don't open external databases directly (the capability to do so is provided for backward compatibility only).

You use the Close method to remove a Database object from the Databases collection without deleting it from disk.  Any open Recordset objects in the database are closed automatically when the Database object is closed.

When a procedure that declares a Database object is finished, these local Database objects are closed along with any open Recordset objects.  Any pending updates are lost and any pending transactions are rolled back, but no trappable error occurs.  It's recommended that you explicitly complete any pending transactions or edits and close Recordset objects and Database objects before exiting procedures that declare these object variables locally.

The first database that is opened is Databases(0).  The Name property setting of a database is a string that specifies the path of the database file.  The Connect property specifies the database type and other parameters used to connect to external databases.  You can refer to any Database object by its Name property setting using this syntax:

Databases("name")

You can also refer to the object by its ordinal number using this syntax (which refers to the first member of the Databases collection):

Databases(0)


See Also

Activating Data Access Objects

Activating Security

Container Object, Containers Collection

CreateDatabase Method

OpenDatabase Method

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Relation Object, Relations Collection

TableDef Object, TableDefs Collection

Workspace Object, Workspaces Collection


Database Object, Databases Collection Example

This example creates a new Database object and opens it (thereby appending it to the Databases collection) in the default Workspace object.  Then it enumerates all the collections contained by each Database object and the properties of the new Database object and closes the new Database.  See the methods and properties listed in the Database summary topic for additional examples.

Function EnumerateDatabase () As Integer

Dim DefaultWorkspace As Workspace

Dim MyDatabase As Database, TempDatabase As Database

Dim I As Integer, J As Integer

Set DefaultWorkspace = Workspaces(0)

Set MyDatabase = DefaultWorkspace.CreateDatabase("MyDB.MDB", _  	dbLangGeneral)

' Enumerate all open databases.

For J = 0 To DefaultWorkspace.Databases.Count - 1

Set TempDatabase = DefaultWorkspace.Databases(J)

Debug.Print

Debug.Print "Enumeration of Databases("; J; "): "; TempDatabase.Name

Debug.Print

' Enumerate containers.

Debug.Print "Container: Name, Owner"

For I = 0 To TempDatabase.Containers.Count - 1

Debug.Print "  "; TempDatabase.Containers(I).Name;

Debug.Print ", "; TempDatabase.Containers(I).Owner

Next I

Debug.Print

' Enumerate query definitions.

Debug.Print "QueryDef: Name"

For I = 0 To TempDatabase.QueryDefs.Count - 1

Debug.Print "  "; TempDatabase.QueryDefs(I).Name

Next I

Debug.Print

' Enumerate recordsets.

' No output because no Recordset is open.

Debug.Print "Recordset: Name"

For I = 0 To TempDatabase.Recordsets.Count - 1

Debug.Print "  "; TempDatabase.Recordsets(I).Name

Next I

Debug.Print

' Enumerate relationships.

Debug.Print "Relation: Name, Table, ForeignTable"

For I = 0 To TempDatabase.Relations.Count - 1

Debug.Print "  "; TempDatabase.Relations(I).Name;

Debug.Print ", "; TempDatabase.Relations(I).Table;

Debug.Print ", "; TempDatabase.Relations(I).ForeignTable

Next I

Debug.Print

' Enumerate table definitions.

Debug.Print "TableDef: Name, DateCreated"

For I = 0 To TempDatabase.TableDefs.Count - 1

Debug.Print "  "; TempDatabase.TableDefs(I).Name;

Debug.Print ", "; TempDatabase.TableDefs(I).DateCreated

Next I

Debug.Print

Next J

' Enumerate built-in properties of MyDatabase.

Debug.Print "MyDatabase.Name: "; MyDatabase.Name

Debug.Print "MyDatabase.CollatingOrder: "; MyDatabase.CollatingOrder

Debug.Print "MyDatabase.Connect: "; MyDatabase.Connect

Debug.Print "MyDatabase.QueryTimeout: "; MyDatabase.QueryTimeout

Debug.Print "MyDatabase.Transactions: "; MyDatabase.Transactions

Debug.Print "MyDatabase.Updatable: "; MyDatabase.Updatable

Debug.Print "MyDatabase.V1xNullBehavior: "; MyDatabase.V1xNullBehavior

Debug.Print

MyDatabase.Close	' File remains on disk.

EnumerateDatabase = True

End Function


Database Object, Databases Collection Properties

Legend

CollatingOrder

Connect

Count

Name

QueryTimeout

RecordsAffected

Transactions

Updatable

Version

V1xNullBehavior


Database Object, Databases Collection Methods

Legend

Close

CreateProperty

CreateQueryDef

CreateRelation

CreateTableDef

Execute

ExecuteSQL

MakeReplica

OpenRecordset

Refresh

Synchronize


Database Object, Databases Collection Summary

Database Object

The Database object contains these collections, methods, and properties.

Collections

Containers	Relations

QueryDefs	TableDefs (default)

Recordsets

Methods

BeginTrans	CreateTableDef

Close	DeleteQueryDef

CommitTrans 	Execute

CreateDynaset	ExecuteSQL

CreateProperty	OpenQueryDef

CreateQueryDef	OpenRecordset

CreateRelation	OpenTable

CreateSnapshot	Rollback

Properties

CollatingOrder	Transactions

Connect	Updatable

Name	Version

QueryTimeout

RecordsAffected

Databases Collection

The Databases collection contains no methods and this property.

Property

Count

Note   If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available.  To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.


DBEngine Object

See Also	Example	Properties	Methods	Summary

The DBEngine object represents the Microsoft Jet database engine.  As the top-level object, it contains and controls all other objects in the hierarchy of data access objects.

Remarks

Use the DBEngine object to control the Jet database engine, manipulate its properties, and perform tasks on temporary objects that aren't elements of collections.  For example, you can:

Use the Version property to obtain the version number of the Jet engine, the LoginTimeout property to obtain or set the ODBC login timeout, and the RegisterDatabase method to provide ODBC information to the Jet engine.

Use the Idle method to enable the Jet engine to complete any pending tasks and the CompactDatabase and RepairDatabase methods to maintain database files.

Use the CreateWorkspace method to create a new session.

Use the Errors collection to examine data access error details.

Set the DBEngine object to Nothing to force reinitialization of the engine when it is next accessed.

Note   If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available. To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.

The DBEngine object is a predefined object, and you can't create additional DBEngine objects.  To refer to a collection belonging to the DBEngine object or to refer to a method or property that applies to this object, use this syntax:

DBEngine.[collection | method | property]

The DBEngine object isn't an element of any collection.

Note   The Microsoft Jet database engine is limited to 10 instances on any particular system.  That is, you can execute up to 10 applications that simultaneously use the Jet version 2.5/3.0 engine.


See Also

Activating Data Access Objects

Activating Security

Data Access Objects and Collections

Error Object, Errors Collection

Property Object, Properties Collection

Workspace Object, Workspaces Collection


DBEngine Object Example

This example enumerates the collections of the DBEngine object.  See the methods and properties of DBEngine for additional examples.

Function EnumerateDBEngine () As Integer

Dim MyWorkspace As Workspace

Dim I As Integer

Debug.Print

Debug.Print "Enumeration of DBEngine"

Debug.Print

' Enumerate all workspaces.

Debug.Print "Workspaces: Name, UserName"

For I = 0 To Workspaces.Count - 1

Set MyWorkspace = Workspaces(I)

Debug.Print "  "; MyWorkspace.Name;

Debug.Print ", "; MyWorkspace.UserName

Next I

Debug.Print

' Enumerate built-in properties.

Debug.Print "DBEngine.Version: "; DBEngine.Version

Debug.Print "DBEngine.LoginTimeout: "; DBEngine.LoginTimeout

Debug.Print

EnumerateDBEngine = True

End Function


DBEngine Object Properties

DefaultPassword

DefaultUser

IniPath

LoginTimeout

Version


DBEngine Object Methods

CompactDatabase

CreateWorkspace

Idle

RegisterDatabase

RepairDatabase


DBEngine Object Summary

The DBEngine object contains these collections, methods, and properties.

Collections

Errors

Properties

Workspaces (default)

Methods

CompactDatabase	RegisterDatabase

CreateWorkspace	RepairDatabase

Idle

Properties

DefaultPassword

DefaultUser

IniPath

LoginTimeout

Version

Note   If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available.  To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.


Dynaset Object

See Also	Properties	Methods	Summary

A Dynaset object is the result of a query that can have updatable records.  Like all recordsets, a Dynaset has records (rows) and fields (columns).  A Dynaset object 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 one or more databases.

Note   The Dynaset object is included for compatibility with earlier versions.  It's recommended that you use the dynaset-type Recordset and its associated methods and properties instead.  The Dynaset object created with the CreateDynaset method is different from the dynaset-type Recordset object.  Although both have similar properties and methods, the dynaset-type Recordset supports significant additional functionality.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.

Remarks

Dynaset objects are created by the Microsoft Jet database engine as a set of locally stored pointers that reference records in database tables.  Only the currently selected record is accessible.

The records aren't brought into memory from the database until the Field objects of the Dynaset are referenced.  At this point, current data is fetched from the database.  If the selected record is no longer available, as when another user has deleted or modified a record, a trappable error occurs.

If there isn't enough local memory to store the Dynaset pointers, the Jet engine saves the Dynaset to TEMP disk space.  If this space is exhausted, a trappable error occurs.

To create a Dynaset for an object variable, use the CreateDynaset method on a Database, another Dynaset, or a QueryDef.

The records of a Dynaset object are returned in no particular order unless you specify an ORDER BY clause in the SQL statement used as an argument to the CreateDynaset method or in a QueryDef.

The default collection of a Dynaset is the Fields collection, and the default property of a Field object is the Value property.  Therefore, the Dynaset object's Value property contains the data for the specified field in the current record.  For example, both of the following statements set the Value property to 99 (where DS is the name of an open Dynaset):

DS.Fields("PubID").Value = 99

DS("PubID") = 99

N$ = "PubID" : DS(N$) = 99

DS(0) = 99

N = 0 : DS(N) = 99

Like all recordsets, when you create a Dynaset the current record is positioned to the first record.  You can use MoveNext, MovePrevious, MoveFirst, or MoveLast to reposition the current record.

Note   The Move method doesn't work with the outdated Dynaset object [image] it's designed to work only with Recordset objects.

You can also use the Find methods, such as FindFirst, to locate a specific record based on a criterion.  If the record isn't found, the NoMatch property is set to True.

To cycle through all records, you can use the BOF and EOF properties to check for the beginning or end of the Dynaset.

When working with ODBC databases and large Dynaset objects, you may discover that using the Find methods or the Sort and Filter properties is unacceptably slow.  To improve performance, use SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or QueryDef objects that call for specific indexed records.

In a multiuser environment, different users can open a Dynaset 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 isn't reflected in any other open Dynaset until it's re-created.  Re-execute the query with a Dynaset to re-create the Dynaset.

If a user deletes a record, other users are notified only when they try to access that record.  If you use pessimistic locking to maintain the integrity of your data, the 2K page containing the current record is locked during Edit and Update operations so that several users can't update the same record at the same time.

Not all Field objects can be updated in all Dynaset objects.  Use the Updatable property of a Field to discover if it's updatable.  Several circumstances can prevent you from being able to update a Dynaset.  See Recordset Object, Recordsets Collection for more information.

Records that you add to your Dynaset are appended to the end of your Dynaset and added to the base table, but other existing Dynaset or Snapshot objects won't include these new records.  Table objects and table-type Recordsets reflect these new records immediately.  Recordsets of all kinds reflect the changes when new objects are created.

A small Snapshot is generally faster to create and access than a Dynaset because its records are either in memory or stored in TEMP disk space, and the Jet engine doesn't have to deal with page locking or multiuser issues.  However, a Snapshot consumes more local resources because the entire record is downloaded to local memory.

You can have more than one Recordset 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 is unloaded.  In the same way, object variables created in a procedure exist only until the procedure is finished.  You should explicitly complete any pending transactions or edits, and close all Dynaset, Snapshot, Table, and Database objects before exiting or completing any procedure containing declarations for these data access objects.

You can also create a copy of a Dynaset with the Clone method.  This takes less memory than creating a new Dynaset using the same records and enables you to use the same bookmarks for both.  The advantage of the Clone method is that you may have two or more current record pointers for the same set of records.

Once a Dynaset is created, you can use the Sort and Filter properties to refine its order or contents.  However, you may find that for larger datasets it may be far more efficient to re-execute the query with a modified ORDER BY or WHERE clause.

The EditMode property indicates when an edit or add operation is in progress. This property is most useful when you want to depart from the default functionality of a Data control or if you aren't using a Data control with Visual Basic Professional Edition.  You can check the value of the EditMode property and the value of the action parameter in the Validate event procedure to determine whether to invoke the UpdateRecord method.  You can also check to see if the LockEdits property setting is True and the EditMode property setting is dbEditInProgress to determine whether the current data page is locked.


See Also

Activating Data Access Objects

Data Access Overview

Dynaset-Type Recordset

Field Object, Fields Collection

ORDER BY Clause

Populating Recordsets

QueryDef Object

Recordset Object, Recordsets Collection

Recordset Property

Snapshot Object

Table Object

WHERE Clause


Dynaset Object Properties

BOF

Bookmark

Bookmarkable

EditMode

EOF

Filter

LockEdits

NoMatch

RecordCount

Sort

Transactions

Updatable


Dynaset Object Methods

AddNew

Clone

Close

CreateDynaset

CreateSnapshot

Delete

Edit

FindFirst

FindLast

FindNext

FindPrevious

ListFields

MoveFirst

MoveLast

MoveNext

MovePrevious

Update


Dynaset Object Summary

The Dynaset object contains these methods and properties.

Methods

AddNew	FindNext

Clone	FindPrevious

Close	ListFields

CreateDynaset	MoveFirst

CreateSnapshot	MoveLast

Delete	MoveNext

Edit	MovePrevious

FindFirst	Update

FindLast

Properties

BOF	NoMatch

Bookmark	RecordCount

Bookmarkable	Sort

EOF	Transactions

Filter	Updatable

LockEdits


Snapshot Object

See Also	Properties	Methods 	Summary

A Snapshot object is the result of a query but doesn't have updatable records.  Like a Recordset, Table, or Dynaset object, 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 and can contain fields from one or more tables in a database.

Note   The Snapshot object is included for compatibility with earlier versions.  It's recommended that you use the snapshot-type Recordset object and its associated methods and properties instead.  The Snapshot created with the CreateSnapshot method is different from the snapshot-type Recordset.  Although both have similar properties and methods, the snapshot-type Recordset supports significant additional functionality.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.

Remarks

The Microsoft Jet database engine creates Snapshot objects by copying records from one or more tables to memory, or, if needed, to disk (or RAM disk) as specified by the TEMP environment variable.  When using Snapshot objects with ODBC tables, data copied to local storage includes any OLE Object or Memo fields, so the amount of local storage needed can be considerable for large Snapshot objects.  You can only access the currently selected record.

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.

The records of Snapshot objects are returned in no particular order unless you specify an ORDER BY clause in the SQL statement or QueryDef.

Like all recordsets, when you create a Snapshot, the current record is positioned on the first record.  You can use MoveNext, MovePrevious, MoveFirst, and MoveLast to move the current record.  If no records qualify for the Snapshot, the RecordCount property setting is 0 and there is no current record.

Note   The Move method doesn't work with the outdated Snapshot object [image] it's designed to work only with Recordset objects.

You can also use the Find methods, such as FindFirst, to locate a record matching a criterion.  If the record isn't located, the NoMatch property is set to True.

Once a Snapshot is created, you can use the Sort and Filter properties to refine its order or contents.  However, you may find that for a larger Snapshot it may be more efficient to re-execute the query with a modified ORDER BY or WHERE clause.

To cycle through all records, you can use the BOF and EOF properties to check for the beginning or end of the Snapshot.

You can also create a copy of a Snapshot with the Clone method.  This uses less memory than creating a new Snapshot on the same records and enables you to use the same bookmarks for both.  The advantage of the Clone method is that you may have two or more "current" record pointers for the same set of records, and their bookmarks can be used interchangeably.

A small Snapshot is generally faster to create and access than a Dynaset because its records are either in memory or stored in TEMP disk space, and the Jet engine doesn't have to deal with page locking or multiuser issues.  However, a Snapshot consumes more resources than a Dynaset because the entire record is downloaded to local memory.  For larger or external databases, a Dynaset can be accessed more quickly.


See Also

Activating Data Access Objects

Data Access Overview

Dynaset Object

Field Object, Fields Collection

ORDER BY Clause

Populating Recordsets

QueryDef Object

Recordset Object, Recordsets Collection

Snapshot-Type Recordset

Table Object

WHERE clause


Snapshot Object Properties

BOF

Bookmark

Bookmarkable

EOF

Filter

RecordCount

Sort


Snapshot Object Methods

Clone

Close

CreateDynaset

CreateSnapshot

FindFirst

FindLast

FindNext

FindPrevious

ListFields

MoveFirst

MoveLast

MoveNext

MovePrevious


Snapshot Object Summary

The Snapshot object contains these methods and properties.

Methods

Clone	FindPrevious

Close	ListFields

CreateDynaset	MoveFirst

CreateSnapshot	MoveLast

FindFirst	MoveNext

FindLast	MovePrevious

FindNext

Properties

BOF	Filter

Bookmark	RecordCount

Bookmarkable	Sort

EOF


Group Object, Groups Collection

See Also	Example	Properties	Methods	Summary

A Group object represents a group of user accounts that have common access permissions when a Workspace object operates as a secure workgroup.

A Groups collection contains all stored Group objects of a Workspace or user account.

Remarks

You create Group objects, and then use their names to establish and enforce access permissions for your databases, tables, and queries using the Document objects that represent the database and database objects (tables and queries) you're working with.

Note   If no SYSTEM.MDW file is available to the Microsoft Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.

You can append an existing Group object to the Groups collection in a User object to establish membership of a user account in that Group object.  Alternatively, you can append a User object to the Users collection in a Group object to give a user account the  permissions of that group.  If you use a Groups or Users collection other than the one to which you just appended an object, you may need to use the Refresh method to refresh the collection with current information from the database.

Using the properties of a Group object, you can:

Check the Name property setting of an existing Group object to determine its name.  You can't check the PID property setting of an existing Group object.

Set the Name and PID properties of a newly created, unappended Group object to establish the identity of that Group object.

The Microsoft Jet database engine predefines three Group objects named Admins, Users, and Guests.

You can refer to a Group object that you create and append to a Groups collection by its Name property setting using this syntax:

Groups("name")

To create a new Group object, use the CreateGroup method on a User or Workspace object.

Note   When using data access objects with Jet database engine version 1.x SYSTEM.MDW files, the Users collection of Group objects and the Groups collection of User objects are always empty.  For example, it isn't possible to determine which groups a user is a member of or which users are in a given group.  The solution is to upgrade your system database to the Jet engine version 3.0 SYSTEM.MDW.  See CompactDatabase method for details.


See Also

Activating Data Access Objects

Activating Security

CreateGroup Method

Document Object, Documents Collection

Property Object, Properties Collection

User Object, Users Collection

Workspace Object, Workspaces Collection


Group Object, Groups Collection; User Object, Users Collection Example

This example illustrates the use of the Group and User objects and the Groups and Users collections.  First it creates a new User object with the Name, PID, and Password property settings of "Pat Smith", "abc123DEF456", and "My Secret" and appends the object to the Users collection of the default Workspace object.  Next it creates a new Group object with the Name and PID property settings of "Accounting" and "UVW987xyz654" and appends the object to the Groups collection of the default Workspace object.  Then the example adds user Pat Smith to the Accounting group.  Finally, it enumerates the User and Group objects in the collections of the default Workspace object.  See the methods and properties listed in the Group and User summary topics for additional examples.

Function EnumerateUserGroup () As Integer

Dim MyWorkspace As Workspace

Dim MyUser As User, TempUser As User

Dim MyGroup As Group, TempGroup As Group

Dim I As Integer, J As Integer

' Create and append new user.

Set MyWorkspace = Workspaces(0)

Set MyUser = MyWorkspace.CreateUser("Pat Smith", "abc123DEF456", "My Secret")

MyWorkspace.Users.Append MyUser

' Create and append new group.

Set MyGroup = MyWorkspace.CreateGroup("Accounting", "UVW987xyz654")

MyWorkspace.Groups.Append MyGroup

' Add new user to new group or converse (do one or the other).

' Use Refresh because both collections are referred to in following code.

' Either add user to group and refresh user.

Set MyUser = MyWorkspace.CreateUser("Pat Smith")

MyWorkspace.Groups![Accounting].Users.Append MyUser

MyWorkspace.Users![Pat Smith].Groups.Refresh

' Or add group to user and refresh group.

'  Set MyGroup = MyWorkspace.CreateGroup("Accounting")

'  MyWorkspace.Users![Pat Smith].Groups.Append MyGroup

'  MyWorkspace.Groups![Accounting].Users.Refresh

' Enumerate all users.

For J = 0 To MyWorkspace.Users.Count - 1

Set TempUser = MyWorkspace.Users(J)

Debug.Print

Debug.Print "Enumeration of Users("; J; "): "; TempUser.Name

Debug.Print

' Enumerate groups.

Debug.Print "Group: Name"

For I = 0 To TempUser.Groups.Count - 1

Debug.Print "  "; TempUser.Groups(I).Name

Next I

Next J

' Enumerate all groups.

For J = 0 To MyWorkspace.Groups.Count - 1

Set TempGroup = MyWorkspace.Groups(J)

Debug.Print

Debug.Print "Enumeration of Groups("; J; "): "; TempGroup.Name

Debug.Print

' Enumerate users.

Debug.Print "User: Name"

For I = 0 To TempGroup.Users.Count - 1

Debug.Print "  "; TempGroup.Users(I).Name

Next I

Next J

EnumerateUserGroup = True

End Function


Group Object,Groups Collection Properties

Legend

Count

Name

PID


Group Object, Groups Collection Methods

Legend

Append

CreateUser

Delete

Refresh


Group Object, Groups Collection Summary

Group Object

The Group object contains these collections, methods, and properties.

Collections

Properties

Users(default)

Method

CreateUser

Properties

Name

PID

Groups Collection

The Groups collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count

Note   If no SYSTEM.MDW file is available to the Microsoft Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.


Parameter Object, Parameters Collection

See Also	Example	Properties	Methods	Summary

A Parameter object represents a parameter associated with a QueryDef object created from a parameter query.

A Parameters collection contains all the Parameter objects of a QueryDef object.

Remarks

Using the properties of a Parameter object, you can set a query parameter that can be changed before the query is run.  You can:

 	Check the Name property setting to determine the name of a parameter.

 	Check or set the Value property (the default property of a Parameter) of a parameter.  For example:

MyQueryDef.Parameters(0) = 5

 	Check the Type property setting to determine the data type of the Parameter.

The Parameters collection provides information only about existing parameters.  You can't append objects to or delete objects from the Parameters collection.

The only method supported by the Parameters collection is Refresh.


 See Also

Activating Data Access Objects

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection


Parameter Object, Parameters Collection Example

This example creates two query parameters for an existing query, runs the query by opening a Recordset from the QueryDef, and then prints the properties of each parameter.  The parameter data types are of type Date.  See the methods and properties listed in the Parameter summary topic for additional examples.

Dim MyDB As Database

Dim MyQuery As QueryDef, MyParameter As Parameter

Dim MyRecordset As Recordset

Dim X As Integer

Set MyDB = Workspaces(0).Databases(0)

Set MyQuery = MyDB.QueryDefs("ParamQuery")	' Open existing QueryDef.

MyQuery.Parameters("Order Date") = "10/11/94"	' Set parameters.

MyQuery.Parameters("Ship Date") = "11/4/94"

Set MyRecordset = MyQuery.OpenRecordset()	' Open Recordset.

For X = 0 To MyQuery.Parameters.Count - 1

Set MyParameter = MyQuery.Parameters(X)

Debug.Print MyParameter.Name	' Print parameter properties.

Debug.Print MyParameter.Type

Debug.Print MyParameter.Value

Next X

MyRecordset.Close


Parameter Object Properties

Legend

Count

Name

Type

Value


Parameter Object, Parameters Collection Methods

Legend

Refresh


Parameter Object, Parameters Collection Summary

Parameter Object

A Parameter object represents a parameter associated with a QueryDef object created from a parameter query.

Properties

Name

Type

Value

Parameters Collection

A Parameters collection contains these methods and this property.

Methods

Append

Refresh

Property

Count


Property Object, Properties Collection (Data Access)

See Also	Example	Properties	Methods	Summary

A Property object represents a built-in characteristic or a user-defined characteristic of a data access object.

A Properties collection contains all the Property objects for a specific instance of an object.

Remarks

Every data access object contains a Properties collection, which has certain built-in Property objects.  These Property objects (which are often just called properties) uniquely characterize that instance of the object.  You specify built-in properties when you create a new data access object.  You can set the properties of some existing data access objects using an assignment statement.

The Property object itself has four built-in properties:

The Name property, a String that uniquely identifies the property.

The Type property, an Integer that specifies the property data type.

The Value property, a Variant that contains the property setting.

The Inherited property, a Boolean flag that indicates whether the property is inherited from another object.  For example, a Field object in a Fields collection of a Recordset object can inherit properties from the underlying TableDef or QueryDef object.

In addition to these built-in properties, you can create and add your own user-defined properties to these objects:

Database, Index, QueryDef, and TableDef objects

Field objects in Fields collections of QueryDef and TableDef objects

To add a user-defined property, use the CreateProperty method to create a Property object with a unique Name property setting.  Set the Type and Value properties of the new Property, and then append it to the Properties collection of the appropriate object.  The object you add the user-defined property to must already be saved on disk (that is, it must be appended to a collection).

You can delete user-defined properties from the Properties collection, but you can't delete built-in properties.

Note   A user-defined property (Property object) is associated only with the specific instance of the object whose Properties collection you append it to.  The property isn't defined for all instances of objects of the selected type.

You can use the Properties collection of an object to enumerate the object's built-in and user-defined properties.  You don't need to know beforehand exactly which properties exist or what their characteristics (Name and Type) are to manipulate them.  However, if you try to check a write-only property (such as the Password property of a Workspace object), an error occurs.

You can refer to an existing built-in or user-defined property by its Name property setting using this syntax:

object.Properties("name")

Or

object.Properties!name

For a built-in property, you can also use this syntax:

object.name

You can also reference properties by their ordinal position with this syntax which refers to the first member of the Properties collection:

object.Properties(0)

Notes   User-defined properties differ from the built-in properties of a data access object in the following ways:

You must refer to them using the full Properties("name") or Properties!name syntax.

Except for user-defined properties, they aren't part of the Properties collection until you change their values from their default values.

If you haven't previously set its value, you need to create it first using the CreateProperty method.  For an example of how to set an application-defined property (or any user-defined property), see the Example.

Properties of Control objects differ from data access object properties in several ways.  The Property objects:

Don't have an Inherited property.

Have a Category property that you can't set.

Can't be enumerated.


See Also

Activating Data Access Objects

CreateProperty Method

Data Access Objects and Collections

Database Object, Databases Collection

Field Object, Fields Collection

Index Object, Indexes Collection

QueryDef Object, QueryDefs Collection

TableDef Object, TableDefs Collection

Workspace Object, Workspaces Collection


Property Object, Properties Collection Example

This example creates a user-defined property for the current database, sets its Type and Value properties, and appends it to the Properties collection of the database.  Then the example enumerates all properties in the database.  See the properties listed in the Property summary topic for additional examples.

Function EnumerateProperty () As Integer

Dim DefaultWorkspace As Workspace

Dim MyDatabase As Database, MyProperty As Property

Dim I As Integer

' Get default workspace and current database.

Set DefaultWorkspace = Workspaces(0)

Set MyDatabase = Workspaces(0).OpenDatabase("MyDB.MDB")

' Create user-defined property.

Set MyProperty = MyDatabase.CreateProperty()

' Set properties of new property.

MyProperty.Name = "UserDefinedProperty"

MyProperty.Type = dbText

MyProperty.Value = "This is a user-defined property."

' Append property to current database.

MyDatabase.Properties.Append MyProperty

' Enumerate all properties of current database.

Debug.Print "Properties of Database "; MyDatabase.Name

For I = 0 To MyDatabase.Properties.Count - 1

Set MyProperty = MyDatabase.Properties(I)

Debug.Print

Debug.Print " Properties("; I; ")"

Debug.Print "  Name: "; MyProperty.Name

Debug.Print "  Type: "; MyProperty.Type

Debug.Print "  Value: "; MyProperty.Value

Debug.Print "  Inherited: "; MyProperty.Inherited

Next I

Debug.Print

EnumerateProperty = True

End Function

This example shows how you can set an application-defined property (or any user-defined property that may not yet exist) without causing a run-time error.  The example sets an arbitrary property of a Field object.  The return value of the function is True if the value was properly set.  The return value is False if an unexpected error occurs when the property is set.  See the properties listed in the Property summary topic for additional examples.

Function SetFieldProperty (MyField As Field, PropertyName As String, PropertyType As Integer, PropertyValue As Variant) As Integer

Const ERR_PROPERTY_NONEXISTENT = 3270

Dim MyProperty As Property

On Error Resume Next	' Function handles errors.

SetFieldProperty = True

MyField.Properties(PropertyName) = PropertyValue

If Err <> 0 Then	' Error occurred when value was set.

If Err <> ERR_PROPERTY_NONEXISTENT

On Error GoTo 0

SetFieldProperty = False

Else

' Create Property object, setting its Name, Type, and Value properties.

On Error Resume Next

Set MyProperty = MyField.CreateProperty(PropertyName, PropertyType, PropertyValue)

MyField.Properties.Append MyProperty

If Err <> 0 Then

SetFieldProperty = False

End If

On Error GoTo 0

End If

End If

End Function


Property Object Properties

Legend

Count

Inherited

Name

Type

Value


Property Object, Properties Collection Methods

Legend

Append

Delete

Refresh


Property Object, Properties Collection Summary

Property Object

The Property object contains no methods and these collections and properties.

Collection

Properties

Properties

Inherited

Name

Type

Value

Properties Collection

The Properties collection contains these methods and this property.

Methods

Append

Delete

Refresh

Property

Count


QueryDef Object, QueryDefs Collection

See Also	Example	Properties	Methods	Summary

A QueryDef object is a stored definition of a query in a Microsoft Jet database.

A QueryDefs collection contains all QueryDef objects in a Database object.

Remarks

The QueryDef object corresponds to a stored query definition in a database.  You can think of a saved query as a compiled SQL statement.

You can use the properties of a QueryDef object to define a query.  For example, you can:

Check and modify the SQL property setting, set its parameters, and then run the query.

Set query parameters using the QueryDef object's Parameters collection.

Set or check the Type property to determine whether the query selects records from an existing table, makes a new table, inserts records from one table into another table, deletes records, or updates records.

Retrieve data from an ODBC data source by setting the ODBCTimeout and Connect properties and, if the query isn't a select query, setting the ReturnsRecords property to False.

Indicate the query is to be passed to an external ODBC server by setting the Connect property, making it an SQL pass-through query.

Use the ReturnsRecords property to indicate that the query returns records.  The ReturnsRecords property is only valid on SQL pass-through queries.

Use the ODBCTimeout property to indicate how long to wait before the query returns records.  ODBCTimeout applies to any query that accesses ODBC data through SQL pass-through, attach without links, or attached ODBC tables.

Queries executed from QueryDef objects run faster than queries specified in the OpenRecordset method because the Microsoft Jet database engine doesn't need to compile the query before executing it.

QueryDef objects are the preferred way to use the native SQL dialect of an external database engine.  For example, you can create a Transact SQL query (as used on Microsoft SQL Server) and store it in a QueryDef object.  When you need to use a non-Jet engine SQL query, you must provide a Connect property string that points to the external data source.  Queries with valid Connect properties bypass the Jet engine and pass the query directly to the external database server for processing:

To create a new QueryDef object, use the CreateQueryDef method.


See Also

Activating Data Access Objects

CreateQueryDef Method

Creating Parameter Queries

Database Object, Databases Collection

Field Object, Fields Collection

Parameter Object, Parameters Collection

Property Object, Properties Collection

Using SQL Pass-Through


QueryDef Object, QueryDefs Collection Example

This example creates a new QueryDef object and appends it to the QueryDefs collection in the current database.  Then the example enumerates all the QueryDef objects in the database and all the properties of the new QueryDef.  See the methods and properties listed in the QueryDef summary topic for additional examples.

Function EnumerateQueryDef () As Integer

Dim MyWorkspace As Workspace, MyDB As Database, MyQuery As QueryDef

Dim I As Integer

Set MyWorkspace = Workspaces(0)

Set MyDB = MyWorkspace.OpenDatabase("MyDB.MDB")

Set MyQuery = MyDB.CreateQueryDef("This is a test")

Debug.Print

' Enumerate QueryDef objects.

Debug.Print

For I = 0 To MyDB.QueryDefs.Count - 1

Debug.Print MyDB.QueryDefs(I).Name

Next I

Debug.Print

' Enumerate built-in properties of MyQuery.

Debug.Print "MyQuery.Name: "; MyQuery.Name

Debug.Print "MyQuery.DateCreated: "; MyQuery.DateCreated

Debug.Print "MyQuery.LastUpdated: "; MyQuery.LastUpdated

Debug.Print "MyQuery.SQL: "; MyQuery.SQL

Debug.Print "MyQuery.ODBCTimeout: "; MyQuery.ODBCTimeout

Debug.Print "MyQuery.Updatable: "; MyQuery.Updatable

Debug.Print "MyQuery.Type: "; MyQuery.Type

Debug.Print "MyQuery.Connect: "; MyQuery.Connect

Debug.Print "MyQuery.ReturnsRecords: "; MyQuery.ReturnsRecords

MyDB.QueryDefs.Delete "This is a test"

EnumerateQueryDef = True

End Function


QueryDef Object,QueryDefs Collection Properties

Legend

Connect

Count

DateCreated

LastUpdated

LogMessages

Name

ODBCTimeout

RecordsAffected

ReturnsRecords

SQL

Type

Updatable


QueryDef Object, QueryDefs Collection Methods

Legend

Append

CreateProperty

Delete

Execute

OpenRecordset

Refresh


QueryDef Object, QueryDefs Collection Summary

QueryDef Object

The QueryDef object contains these collections, methods, and properties.

Collections

Fields

Parameters (default)

Methods

Close

CreateProperty

Execute

OpenRecordset

Properties

Connect	ODBCTimeout

DateCreated	RecordsAffected

LastUpdated	ReturnsRecords

LogMessages	SQL

Name	Type

QueryDefs Collection

The QueryDefs collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Recordset Object, Recordsets Collection

See Also	Example	Properties	Methods

A Recordset object represents the records in a base table or the records that result from running a query.

The Recordsets collection contains all open Recordset objects in a Database object.

Note   Version 1.1 of the Jet database engine supported the Table, Dynaset, and Snapshot data access objects.  Although these objects are supported in the Jet engine version 2.5/3.0, they aren't the same as the table-type, dynaset-type, and snapshot-type Recordset objects.  These data access objects have similar properties and methods; however, the Recordset object supports significant additional functionality.

It's recommended that you use the table-type, dynaset-type, and snapshot-type Recordset objects and their associated methods and properties instead.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.

Remarks

When you use data access objects, you interact with data almost entirely using Recordset objects.  All Recordset objects are constructed using records (rows) and fields (columns).  There are three types of Recordset objects:

Table-type Recordset [image] a representation in code of a base table that you can use to add, change, or delete records from a single database table.

Dynaset-type Recordset [image] the result of a query that can have updatable records.  A dynaset-type Recordset is a dynamic set of records that you can use to add, change, or delete records from an underlying database table or tables.  A dynaset-type Recordset can contain fields from one or more tables in a database.

Snapshot-type Recordset [image] a static copy of a set of records that you can use to find data or generate reports.  A snapshot-type Recordset can contain fields from one or more tables in a database but can't be updated.

Note   If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available.  To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.

You can choose the type of Recordset object you want to create using the type argument of the OpenRecordset method.  If you don't specify a type, the Microsoft Jet database engine attempts to create a table-type Recordset.  If this isn't possible, the Jet engine creates a dynaset-type or snapshot-type Recordset.

When creating a Recordset using a nonattached TableDef object, only table-type Recordset objects are created.  Only dynaset-type or snapshot-type Recordsets can be created with attached tables or tables in external ODBC databases.

The Type property indicates the type of Recordset created and the Updatable property indicates whether or not you can change the object's records.

A new Recordset is automatically added to the Recordsets collection when you open the object, and it's automatically removed when you close it.

Information about the structure of a base table, such as the names and field data types of each Field and any Index objects, is stored in a TableDef.

Note   If you use variables to represent a Recordset object and the Database object that contains the recordset, make sure the variables have the same scope, or lifetime.  For example, if you declare a global variable that represents a Recordset, make sure the variable that represents the database containing the recordset is also global or is declared in a Sub or Function procedure using the Static keyword.

Your application can create as many Recordset object variables as needed.  A Recordset can refer to one or more tables, queries alone, or queries referenced by other Recordset objects in any combination.  You can also have a Recordset that refers to some or all of the fields or records in other Recordset objects.

Dynaset- and snapshot-type Recordsets are stored in local memory. If there isn't enough space in local memory to store the data, the Jet engine saves the additional data to TEMP disk space.  If this space is exhausted, a trappable error occurs.

The default collection of a Recordset is the Fields collection, and the default property of a Field object is the Value property.  You can simplify your code by taking advantage of these defaults.  For example, the following lines of code all set the value of the PubID field in the current record of a Recordset:

MyTable.Fields("PubID").Value = 99

MyTable("PubID") = 99

MyTable!PubID = 99

When you create a Recordset, the current record is positioned to the first record if there are any records.  If there are no records, the RecordCount property setting is 0, and the BOF and EOF property settings are True.

You can use the MoveNext, MovePrevious, MoveFirst, and MoveLast methods to reposition the current record.  For dynaset-type and snapshot-type Recordsets, you can also use the Find methods, such as FindFirst, to locate a specific record based on a criterion.  If the record isn't found, the NoMatch property is set to True.

To cycle through all records, you can use the BOF and EOF properties to check for the beginning or end of the Recordset.  However, it may be faster to write an SQL query to perform operations that apply to an entire set of records.

You can have more than one Recordset 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 is unloaded.  In the same way, object variables created in a procedure exist only until the procedure has finished.  Explicitly complete any pending transactions or edits, and close all Recordset and Database objects before exiting or completing any procedure containing declarations for these data access objects.


See Also

Activating Data Access Objects

Database Object, Databases Collection

Dynaset-Type Recordset

Field Object, Fields Collection

Index Object, Indexes Collection

Populating Recordsets

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection

Snapshot-Type Recordset

Table-Type Recordset

TableDef Object, TableDefs Collection


Recordset Object, Recordsets Collection Example

This example creates a new Recordset object and opens it (thereby appending it to the Recordsets collection) in the default database.  Then the example enumerates all the Recordset objects in the current database and all the fields in each Recordset object and closes the new Recordset.  See the methods and properties in the Recordset summary topic for additional examples.

Function EnumerateRecordset () As Integer

Dim MyDB As Database, MyData As Recordset, TempRecordset As Recordset

Dim I As Integer, J As Integer

Set MyDB = Workspaces(0).OpenDatabase("MyDB.MDB")

Set MyData = MyDB.OpenRecordset("Orders", dbOpenSnapshot)

Debug.Print

' Enumerate all Recordset objects.

For J = 0 To MyDB.Recordsets.Count - 1

Set TempRecordset = MyDB.Recordsets(J)

Debug.Print

Debug.Print "Enumeration of Recordset objects("; J; "): "; TempRecordset.Name

Debug.Print

' Enumerate fields.

Debug.Print "Fields: Name, Type, Value"

For I = 0 To TempRecordset.Fields.Count - 1

Debug.Print "  "; TempRecordset.Fields(I).Name

Debug.Print ", "; TempRecordset.Fields(I).Type

If TempRecordset.Fields(I).Type = dbText Then

Debug.Print ", "; TempRecordset.Fields(I).Value

End if

Next I

Next J

MyData.Close

MyDB.Close

EnumerateRecordset = True

End Function


Recordset Object, Recordsets Collection Properties

Recordset Object

The Microsoft Jet database engine version 2.5/3.0 supports an enhanced Recordset object.  In addition, the outdated Dynaset, Table, and Snapshot objects provided by the Jet engine version 1.x are also supported.  In some cases, several properties aren't supported when working with the outdated objects.  The following table indicates which properties apply to each type of Recordset object and whether the property setting is read/write, read-only, or always False.

Note   Snapshot-type Recordset objects that are created when you use dbForwardOnly as the options argument with the OpenRecordset method don't support the methods and properties marked with an asterisk (*).  In addition, the Move method works only with forward moves that don't use a bookmark offset.

Read-only

Read/write

Jet engine version 2.5/3.0	Jet engine version 1.x
Recordset object types	Recordset objects

Property	Dynaset	Snapshot	Table	Dynaset	Snapshot	Table

AbsolutePosition

BOF

Bookmark	*

Bookmarkable	*

CacheSize

CacheStart

DateCreated

EditMode

EOF

Filter

Index

LastModified

LastUpdated

LockEdits

Name

NoMatch

PercentPosition	*

RecordCount

Restartable	False

Sort

Transactions	False	False

Type

Updatable	False	False

ValidationRule

ValidationText

Recordsets Collection

The Recordsets collection contains this property:

Property

Count


Recordset Object, Recordsets Collection Methods

Recordset Object

The Microsoft Jet database engine version 2.5/3.0 supports an enhanced Recordset object.  In addition, the outdated Dynaset, Table, and Snapshot objects provided by the Jet engine version 1.x are also supported.  In some cases, several methods aren't supported when working with the outdated objects.  The following table lists recordset methods and which objects support them.

Note   Snapshot-type Recordset objects created when you use dbForwardOnly as the options argument with the OpenRecordset method don't support the methods and properties marked with an asterisk (*).  In addition, the Move method works only with forward moves that don't use a bookmark offset.

Jet engine version 2.5/3.0	Jet engine version 1.x
Recordset object types	Recordset objects

Method	Dynaset	Snapshot	Table	Dynaset	Snapshot	Table

AddNew

CancelUpdate

Clone	*

Close

CopyQueryDef

Delete

Edit

FillCache

FindFirst	*

FindLast	*

FindNext	*

FindPrevious	*

GetRows

Move	*

MoveFirst	*

MoveLast	*

MoveNext

MovePrevious	*

OpenRecordset	*

Requery

Seek

Update

Recordsets Collection

The Recordsets collection contains this method.

Method

Refresh


Relation Object, Relations Collection

See Also	Example	Properties	Methods 	Summary

A Relation object represents a relationship between fields in tables or queries.

A Relations collection contains stored Relation objects of a Database object.

Remarks

You can use the Relation object to create new relationships and examine existing relationships in your database.  By setting the Attributes property, you can also use the Microsoft Jet database engine to enforce referential integrity.

Any changes you make to the database that violate the relationships established for the database result in a trappable error.  If you request cascade update or cascade delete operations, the Jet database engine also modifies the primary or foreign key tables to enforce the relationships you establish.

An example of a typical relationship can be found between the NameAddress table and the ValidStateCodes table. The State field of the NameAddress table is the primary key, and the State field of the ValidStateCodes table is the foreign key.  For a new record to be accepted in the NameAddress table, the Jet engine searches the ValidStateCodes table for a match on the State field of the NameAddress table.  If no match is found, the Jet engine doesn't accept the new record, and a trappable error occurs.

Using a Relation object and its properties, you can:

Specify an enforced relationship between fields in base tables (but not a relationship that involves a query or an attached table).

Establish unenforced relationships between any type of table or query [image] native or attached.

Use the Name property to refer to the relationship between the fields in the referenced primary table and the referencing foreign table.

Use the Attributes property to determine whether the relationship between fields in the table is one-to-one or one-to-many and how to enforce referential integrity.

Use the Attributes property to determine whether the Microsoft Jet database engine can perform cascade update and cascade delete operations on primary and/or foreign tables.

Use the Attributes property to determine whether the relationship between fields in the table is left join or right join.

Notes

The Name property settings of all Field objects in the Fields collection of a Relation object represent the names of the fields in the primary key of the referenced table.  The ForeignName property settings of the Field objects represent the names of the fields in the foreign key of the referencing table.

When you enforce referential integrity, a unique index must already exist for the key field of the referenced table.  The Jet database engine automatically creates an index with the Foreign property set to act as the foreign key in the referencing table.

If no SYSTEM.MDW file is available to the Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.

To create a new Relation object, use the CreateRelation method.


See Also

Activating Data Access Objects

Activating Security

CreateRelation Method

Database Object, Databases Collection

Field Object, Fields Collection

Foreign Property

Property Object, Properties Collection


Relation Object, Relations Collection Example

This example creates a one-to-many relationship between single fields in two tables.  Because referential integrity is enforced for the relationship, an index is created for the primary table.  See the methods and properties listed in the Relation summary topic for additional examples.

Function EnumerateRelation () As Integer

Dim MyDatabase As Database

Dim MyTableDef As TableDef, MyField As Field

Dim MyIndex As Index, MyRelation As Relation

Dim I As Integer

' Get database.

Set MyDatabase = Workspaces(0).OpenDatabase("MyDB.MDB")

' Create referenced table with primary key.

Set MyTableDef = MyDatabase.CreateTableDef("Referenced")

Set MyField = MyTableDef.CreateField("PrimaryKey", dbLong)

MyTableDef.Fields.Append MyField

' Create unique index for enforced referential integrity.

Set MyIndex = MyTableDef.CreateIndex("UniqueIndex")

MyIndex.Primary = True ' No Null values allowed.

Set MyField = MyTableDef.CreateField("PrimaryKey")

MyIndex.Fields.Append MyField

MyTableDef.Indexes.Append MyIndex

MyDatabase.TableDefs.Append MyTableDef

' Create referencing table with foreign key.

Set MyTableDef = MyDatabase.CreateTableDef("Referencing")

Set MyField = MyTableDef.CreateField("ForeignKey", dbLong)

MyTableDef.Fields.Append MyField

MyDatabase.TableDefs.Append MyTableDef

' Create one-to-many relationship and enforce referential integrity.

Set MyRelation = MyDatabase.CreateRelation("EnforcedOneToMany")

MyRelation.Table = "Referenced"

MyRelation.ForeignTable = "Referencing"

' Don't set either dbRelationUnique or dbRelationDontEnforce.

MyRelation.Attributes = 0

Set MyField = MyRelation.CreateField("PrimaryKey")

MyField.ForeignName = "ForeignKey"

MyRelation.Fields.Append MyField

MyDatabase.Relations.Append MyRelation

' Enumerate relation and its fields.

Debug.Print "Relation: "; MyRelation.Name

Debug.Print "  Primary Table: "; MyRelation.Table

Debug.Print "  Foreign Table: "; MyRelation.ForeignTable

Debug.Print "  Attributes: "; MyRelation.Attributes

Debug.Print "Fields in Relation: Primary, Foreign";

For I = 0 To MyRelation.Fields.Count - 1

Set MyField = MyRelation.Fields(I)

Debug.Print "  "; MyField.Name;

Debug.Print ", "; MyField.ForeignName

Next I

Debug.Print

MyDatabase.Relations.Delete "EnforcedOneToMany"

MyDatabase.TableDefs.Delete "Referenced"

MyDatabase.TableDefs.Delete "Referencing"

EnumerateRelation = True

End Function


Relation Object,Relations Collection Properties

Legend

Attributes

Count

ForeignTable

Name

Table


Relation Object, Relations Collection Methods

Legend

Append

CreateField

Delete

Refresh


Relation Object, Relations Collection Summary

Relation Object

The Relation object contains these collections, methods, and properties.

Collections

Fields (default)

Properties

Methods

CreateField

Properties

Attributes

ForeignTable

Name

Table

Relations Collection

The Relations collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


TableDef Object, TableDefs Collection

See Also	Example	Properties	Methods	Summary

A TableDef object represents the stored definition of a base table or an attached table.

A TableDefs collection contains all stored TableDef objects in a database.

Remarks

You manipulate a table definition using a TableDef object and its methods and properties.  For example, you can:

Examine the field and index structure of any local, attached, or external table in a database.

Read or write the Connect and SourceTableName property settings for attached tables, and use the RefreshLink method to update connections to attached tables.

Read (or write, if the Updatable property is set to True) the ValidationRule and ValidationText property settings to find (or specify) validation conditions.

Use the OpenRecordset method to create a table-, dynaset-, or snapshot-type Recordset object based on the table definition.

The default collection of a Database object is the TableDefs collection, and the default collection of a TableDef object is the Fields collection.  The default property of a TableDef is the Name property.  You can simplify your code by using 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 isn't the same as the name of an object variable to which it's assigned.

For base tables, the RecordCount property contains the number of records in the specified database table.  For attached tables the RecordCount property setting is always -1.

You refer to a TableDef object that you create and append to a TableDefs collection by its Name property setting using this syntax:

TableDefs("name")

To create a new TableDef object, use the CreateTableDef method.

To make changes in the structure of a table, such as adding a field

1.	Make sure any Recordset objects based on the table are closed by all users.

2.	Create a Field object variable and set its properties using the CreateField method.

3.	Add the Field to the Fields collection of the TableDef with the Append method.

To create a table that is ready for new records in a database

1.	Create a TableDef object using the CreateTableDef method.

2.	Set its properties.

3.	Create a Field object variable and set its properties using the CreateField method for each field in the table.

4. 	Add the fields to the Fields collection of the TableDef with the Append method.

5.	Use the Append method to add the new TableDef to the TableDefs collection of the Database.

An attached table is linked to the database by the SourceTableName and Connect properties of the TableDef object.

To attach a table to a database

1.	Create a TableDef object using the CreateTableDef method.

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 can delete a Field from a TableDefs collection if it doesn't have any indexes assigned to it, but its underlying data is lost.

To change a table definition using Microsoft Access or in code

1.	Back up the table or field data.

2.	Delete a specified TableDef from the TableDefs collection or Field from the Fields collection (which also deletes the data).

3.	Create and append your revised TableDef or Field.

4.	Reload the data.


See Also

Activating Data Access Objects

CreateTableDef Method

Database Object, Databases Collection

Field Object, Fields Collection

Index Object, Indexes Collection

Property Object, Properties Collection

Recordset Object, Recordsets Collection


TableDef Object, TableDefs Collection Example

This example creates a new TableDef object, adds a Field object to it, and appends the TableDef to the TableDefs collection in the current database.  Then the example enumerates all the TableDef objects in the current database and all the properties of the new TableDef.  See the methods and properties listed in the TableDef summary topic for additional examples.

Function EnumerateTableDef () As Integer

Dim MyDatabase As Database

Dim MyTableDef As TableDef

Dim MyField As Field

Dim I As Integer

Set MyDatabase = Workspaces(0).OpenDatabase("MyDB.MDB")

Set MyTableDef = MyDatabase.CreateTableDef("MyTable")

Set MyField = MyTableDef.CreateField("MyField", dbDate)

MyTableDef.Fields.Append MyField

MyDatabase.TableDefs.Append MyTableDef

' Get database name.

Debug.Print "Database Name: "; MyDatabase.Name

' Enumerate all fields in MyTableDef.

Debug.Print "TableDef: Name; Field: Name"

For I = 0 To MyTableDef.Fields.Count - 1

Debug.Print "  "; MyTableDef.Name;

Debug.Print "; "; MyTableDef.Fields(I).Name

Next I

Debug.Print

' Enumerate all indexes in MyTableDef.

Debug.Print "TableDef: Name; Index: Name"

For I = 0 To MyTableDef.Indexes.Count - 1

Debug.Print "  "; MyTableDef.Name;

Debug.Print "; "; MyTableDef.Indexes(I).Name

Next I

Debug.Print

' Enumerate built-in properties of MyTableDef.

Debug.Print "MyTableDef.Name: "; MyTableDef.Name

Debug.Print "MyTableDef.Attributes: "; MyTableDef.Attributes

Debug.Print "MyTableDef.Connect: "; MyTableDef.Connect

Debug.Print "MyTableDef.DateCreated: "; MyTableDef.DateCreated

Debug.Print "MyTableDef.LastUpdated: "; MyTableDef.LastUpdated

Debug.Print "MyTableDef.RecordCount: "; MyTableDef.RecordCount

Debug.Print "MyTableDef.SourceTableName: "; MyTableDef.SourceTableName

Debug.Print "MyTableDef.Updatable: "; MyTableDef.Updatable

Debug.Print "MyTableDef.ValidationRule: "; MyTableDef.ValidationRule

Debug.Print "MyTableDef.ValidationText: "; MyTableDef.ValidationText

EnumerateTableDef = True

End Function


TableDef Object, TableDefs Collection Properties

Legend

Attributes

ConflictTable

Connect

Count

DateCreated

LastUpdated

Name

RecordCount

SourceTableName

Updatable

ValidationRule

ValidationText


TableDef Object, TableDefs Collection Methods

Legend

Append

CreateField

CreateIndex

CreateProperty

Delete

OpenRecordset

Refresh

RefreshLink


Tabledefs Obect, TableDefs Collection Summary

TableDef Object

A TableDef object contains these collections, methods, and properties.

Collections

Fields (default)

Indexes

Properties

Methods

CreateField

CreateIndex

CreateProperty

OpenRecordset

RefreshLink

Properties

Attributes	RecordCount

Connect	SourceTableName

DateCreated	Updatable

LastUpdated	ValidationRule

Name	ValidationText

A TableDef object may also contain application-defined properties.  For details on reading and setting these properties, refer to the application's online Help.

TableDefs Collection

A TableDefs collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count

Note   If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available.  To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the References dialog box.  For more information, see Activating Data Access Objects.


User Object, Users Collection

See Also	Properties	Methods 	Summary

A User object represents a user account that has access permissions when a Workspace object operates as a secure workgroup.

A Users collection contains all stored User objects of a Workspace or group account.

Remarks

You create User objects, and then use their names to establish and enforce access permissions for your databases, tables, and queries using the Document objects that represent the database or database objects (tables and queries) you're working with.  Also, if you know the properties of a specific User object, you can create a new Workspace object that has the same access permissions as the User object.

You can append an existing User object to the Users collection of a Group object to give a user account the access permissions for that Group object.  Alternatively, you can append the Group object to the Groups collection in a User object to establish membership of the user account in that group.  If you use a Users or Groups collection other than the one to which you just appended an object, you may need to use the Refresh method.

Using the properties of a User object, you can:

Check the Name property setting of an existing User object to determine its name.  You can't check the PID and Password property settings of an existing User object.

Set the Name, PID, and Password properties of a newly created, unappended User object to establish the identity of that User object.  If you don't set the Password property, it's set to a zero-length string ("").

The Microsoft Jet database engine predefines two User objects named Admin and Guest.  The user Admin is a member of the Group objects named Admins and Users; the user Guest is a member only of the Group object named Guests.

You can refer to any other User object that you create and append to a Users collection by its Name property setting using this syntax:

Workspaces(n)|Group.Users("name")

To create a new User object, use the CreateUser method.

Notes

If no SYSTEM.MDW file is available to the Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.

When using data access objects with Microsoft Jet engine version 1.x SYSTEM.MDW files, the Users collection of a Group object is always empty.  For example, it isn't possible to determine which groups a user is a member of or which users are in a given group.  The solution is to upgrade your system database to a Jet engine version 3.0 SYSTEM.MDW.  See CompactDatabase method for details.

If you're using a Microsoft Access version 1.x or later SYSTEM.MDW or SYSTEM.MDA database, you can't refer to User objects in a Group object's Users collection or append to that collection.  However, you can refer to User objects in a Workspace object's Users collection, and append to that Users collection.  You can also refer to Group objects in a User object's Groups collection, and append to that collection.


See Also

Activating Data Access Objects

Activating Security

CreateUser Method

Document Object, Documents Collection

Group Object, Groups Collection

Property Object, Properties Collection

Workspace Object, Workspaces Collection


User Object, Users Collection Properties

Legend

Count

Name

Password

PID


User Object, Users Collection Methods

Legend

Append

CreateGroup

Delete

NewPassword

Refresh


User Object, Users Collection Summary

User Object

The User object contains these collections, methods, and properties.

Collections

Groups (default)

Properties

Methods

CreateGroup

NewPassword

Properties

Name

Password

PID

Users Collection

The Users collection contains these methods and properties.

Methods

Append

Delete

Refresh

Property

Count


Workspace Object, Workspaces Collection

See Also	Example	Properties	Methods 	Summary

A Workspace object defines a session for a user.  It contains open databases and provides mechanisms for simultaneous transactions and for a secure workgroup.

The Workspaces collection contains all active, unhidden Workspace objects of the DBEngine object.

Remarks

Use the Workspace object to manage the current session or to start an additional session.  In a session, you can open multiple databases, manage transactions, and establish security based on user names and passwords.  For example, you can:

Create a Workspace object using the Name, Password, and UserName properties to establish a named, password-protected session.  The session creates a scope in which you can open multiple databases and conduct one instance of nested transactions.  Use the Close method to terminate a session.

Use the OpenDatabase method to open one or more existing databases on that Workspace.

Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction processing within a Workspace and use several Workspace objects to conduct multiple, simultaneous, and overlapping transactions.

Use the IsolateODBCTrans property to isolate multiple transactions that involve the same ODBC database.

Notes

If your project doesn't reference the Data Access (DA) object library in the Object Browser, none of the data access objects are available.  To make these objects available, choose References from the Tools menu and select the appropriate DAO Component Object Library in the  References dialog box.  For more information, see Activating Data Access Objects.

If no SYSTEM.MDW file is available to the Microsoft Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.

When you start the Jet database engine, you automatically create the default workspace, DBEngine.Workspaces(0).  The settings of the Name and UserName properties of the default workspace are "#Default Workspace#" and "Admin", respectively.  If security is enabled, the UserName property setting is the name of the user who logged on.  If you use the OpenDatabase method without specifying a Workspace object, the default DBEngine.Workspaces(0) is used.

When you use transactions, all databases in the specified Workspace are affected [image] even if multiple Database objects are opened in the Workspace.  For example, if you use a BeginTrans method, update several records in a database, and then delete records in another database, when you use the Rollback method, both the update and delete operations are rolled back.  You can create additional Workspace objects to manage transactions independently across Database objects.

Workspace objects are created with the CreateWorkspace method of the DBEngine object.  Once created, new Workspace objects must be appended to the Workspaces collection if you need to refer to them from the Workspaces collection.  You can, however, use newly created Workspace objects without appending them to the Workspaces collection.

You can refer to any other Workspace object that you create and append to the collection by its Name property setting using this syntax:

Workspaces("name")

You can also refer to appended Workspace objects by their position in the Workspaces collection using this syntax (where n is the nth member of the Workspaces collection):

DBEngine.Workspaces(n)


See Also

Activating Data Access Objects

Activating Security

CreateWorkspace Method

Database Object, Databases Collection

DBEngine Object

Group Object, Groups Collection

Property Object, Properties Collection

User Object, Users Collection


Workspace Object, Workspaces Collection Example

This example creates a new Workspace and appends it to the Workspaces collection.  It assumes that the user JustAUser with a password of Secret has already been created.  The example enumerates the collections of each Workspace object and finally closes the new Workspace.  See the methods and properties of the Workspace object or Workspaces collection for additional examples.

Function EnumerateWorkspace () As Integer

Dim AnyWorkspace As Workspace, NewWorkspace As Workspace

Dim I As Integer, J As Integer

' NOTE: Insert the path to your .INI file in this line.

   DBEngine.IniPath = "C:\MYAPPDIR\MYAPP.INI"

   ' Create new workspace and add it to collection.

Set NewWorkspace = DBEngine.CreateWorkspace("NewWorkspace",

    "JustAUser", "Secret")

DBEngine.Workspaces.Append NewWorkspace

' Enumerate all workspaces.

For J = 0 To DBEngine.Workspaces.Count - 1

Set AnyWorkspace = DBEngine.Workspaces(J)

Debug.Print

Debug.Print "Enumeration of Workspaces("; J; "): "; AnyWorkspace.Name

Debug.Print

' Enumerate databases.

Debug.Print "Databases: Name"

For I = 0 To AnyWorkspace.Databases.Count - 1

Debug.Print "  "; AnyWorkspace.Databases(I).Name

Next I

' Enumerate all user accounts.

Debug.Print "Users: Name"

For I = 0 To AnyWorkspace.Users.Count - 1

Debug.Print "  "; AnyWorkspace.Users(I).Name

Next I

Debug.Print

' Enumerate all group accounts.

Debug.Print "Groups: Name"

For I = 0 To AnyWorkspace.Groups.Count - 1

Debug.Print "  "; AnyWorkspace.Groups(I).Name

Next I

Debug.Print

Next J

Debug.Print

' Enumerate built-in properties of NewWorkspace.

Debug.Print "NewWorkspace.Name: "; NewWorkspace.Name

Debug.Print "NewWorkspace.UserName: "; NewWorkspace.UserName

Debug.Print

NewWorkspace.Close

EnumerateWorkspace = True

End Function


Workspace Object, Workspaces Collection Properties

Legend

Count

IsolateODBCTrans

Name

UserName


Workspace Object, Workspaces Collection Methods

Legend

Append

BeginTrans

Close

CommitTrans

CreateDatabase

CreateGroup

CreateUser

Delete

OpenDatabase

Refresh

Rollback


Workspace Object, Workspaces Collection Summary

Workspace Object

The Workspace object contains these collections, methods, and properties.

Collections

Databases (default)

Groups

Users

Methods

BeginTrans	CreateGroup

Close	CreateUser

CommitTrans	OpenDatabase

CreateDatabase	Rollback

Properties

Name

UserName

Workspaces Collection

The Workspaces collection contains this method and property.

Method

Refresh

Property

Count


Document Object, Documents Collection

See Also	Properties	Methods 	Summary

A Document object includes information about one instance of a type of object.  The object can be a database, saved table, query, or relationship.

A Documents collection contains all of the Document objects for a specific type of object.

Remarks

Each Container object has a Documents collection containing Document objects that describe instances of built-in Container types.  The following table lists the type of object each Document describes, the name of its Container object, and what type of information Document contains.

Document	Container	Contains information about

Database	Databases	Containing database

Table or query	Tables	Saved table or query

Relationship	Relationships	Saved relationship

Note   Don't confuse the particular types of Container objects with the collection types of the same name.  For example, the Databases Container object refers to all saved objects of the specified type, but the Databases collection refers only to open objects of the specified type.

Because a Document object corresponds to an existing database object, you can't create new Document objects or delete existing ones.  Using the properties of an existing Document object, you can:

Determine the name that a user or the Microsoft Jet database engine gave to the object when it was created by checking the Name property setting.

Determine or specify the owner of the database object by checking or setting the Owner property.  To set the Owner property, you must have write permission for the Document object, and you must set the property to the name of an existing User or Group object.

Determine the name of the Container object that contains the Document object by checking the Container property setting.

Determine or specify the access permissions of a user or group for the object by checking or setting the UserName or Permissions property.  To set these properties, you must have write permission for the Document object, and you must set the UserName property to the name of an existing User or Group object.

Determine the date and time when the Document object was created and last modified by checking the DateCreated and LastUpdated property settings.

You can refer to a Document object by its Name property setting using this syntax:

MyContainer.Documents("name")


See Also

Activating Data Access Objects

Activating Security

Container Object, Containers Collection

Group Object, Groups Collection

Property Object, Properties Collection

User Object, Users Collection


Document Object, Documents Collection Properties

Legend

AllPermissions

Container

Count

DateCreated

LastUpdated

Name

Owner

Permissions

UserName


Document Object, Documents Collection Methods

Legend

Refresh


Document Object, Documents Collection Summary

Document Object

The Document object contains no methods and these collections and properties.

Collection

Properties

Properties

Container	Owner

DateCreated	Permissions

LastUpdated	UserName

Name

Documents Collection

The Documents collection contains these methods and this property.

Methods

Refresh

Property

Count


Dynaset-Type Recordset

See Also	Example	Properties	Methods

A dynaset-type Recordset is a type of Recordset object that you can use to manipulate data in an underlying table or tables.  A dynaset-type Recordset is a dynamic set of records that can contain fields from one or more tables or queries in a database and may be updatable.

Note   The dynaset-type Recordset replaces the Dynaset object.

Remarks

A dynaset-type Recordset is different from a snapshot-type Recordset because only a unique key for each record is brought into memory, instead of actual data.  As a result, a dynaset is normally updated with changes made to the source data, while the snapshot is not.  Like the table-type Recordset, a dynaset's current record is fetched only when its fields are referenced.

To create a dynaset-type Recordset, use the OpenRecordset on an open database, against another dynaset- or snapshot-type Recordset, or on a QueryDef object.

If you request a dynaset-type Recordset and the Microsoft Jet database engine is unable to gain read-write access to the records, the Jet engine may create a read-only dynaset-type Recordset.  If the Recordset created isn't updatable, the Updatable property setting is False.

As base table data changes due to updates made by your application or by other users, current data is available to your application when you reposition the current record.  In a multiuser database, more than one user can open a dynaset-type Recordset referring to the same records.  Because a dynaset-type Recordset is dynamic, when one user changes a record, other users have immediate access to the changed data.  However, if one user adds a record, other users aren't notified until they use the Requery method on the Recordset.  If a user deletes a record, other users are notified when they try to access it.

Records added to the database don't become a part of your dynaset-type Recordset unless you add them using the AddNew method.  For example, if you use an action query containing an INSERT INTO SQL statement to add records, the new records aren't included in your dynaset-type Recordset until you use the Requery method or you rebuild your Recordset using the OpenRecordset method.

To maintain data integrity, dynaset- and table-type Recordset objects are locked during Edit and Update operations so that only one user can update a particular record at a time.  When the Jet database engine locks a record, it locks the entire 2K page containing the record.

Two kinds of locking are used with non-ODBC tables [image] pessimistic and optimistic.  External tables accessed using ODBC always use optimistic locking.  The locking conditions in effect during editing are determined by the LockEdits property.

Not all fields can be updated in all dynaset-type Recordset objects.  To determine whether you can update a particular field, check the Updatable property setting of the Field object.

Some of the reasons a dynaset-type Recordset may not be updatable are:

There isn't a unique index on the ODBC or Paradox table(s).

The data page is locked by another user.

The record has changed since you last read it.

The user doesn't have permission.

One or more of the tables or fields are set to Read-Only.

The database is opened as Read-Only.

The Recordset was created from multiple tables without a JOIN statement or the query was too complex.

The order of dynaset-type Recordset or Recordset data isn't guaranteed to follow any specific sequence.  If you need to order your data, use an SQL statement with an ORDER BY clause to create the Recordset.  This technique can also be used to filter the records so that only certain records are added to the Recordset.  For example, the following code selects only titles that were published between 1993 and 1994 and sorts the resulting records by title:

Dim Db As Database, Rs As Recordset, SQL As String

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")

SQL$ = "SELECT * FROM Titles  " _

& " WHERE [Year Published] BETWEEN 1993 AND 1994 " _

& " ORDER BY ISBN;"

Set Rs = Db.OpenRecordset(SQL$,dbOpenDynaset)

Using this technique instead of the Filter or Sort properties or testing each record individually generally results in faster access to your data.


Dynaset-Type Recordset Example

This example creates a new dynaset-type Recordset object and opens it, appending it to the Recordsets collection in the default database.  It then edits the record(s).

Function ChangeSQL () As Integer

Dim MyDB As Database, MyData As Recordset

Dim I As Integer, J As Integer, SQL As String

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

SQL$ = "Select * From Titles Where Title = 'Using SQL' "

Set MyData = MyDB.OpenRecordset(SQL$, dbOpenDynaset)

If MyData.RecordCount > 0 and MyData.Updatable Then

Do Until MyData.EOF

MyData.Edit

MyData![Year Published] = 1994	' Change year published.

MyData.Update

MyData.MoveNext

Loop

Else

Debug.Print "No such title or table not updatable"

End If

MyData.Close

MyDb.Close

ChangeSQL = True

End Function


See Also

Activating Data Access Objects

Dynaset Object

Edit Method

Field Object, Fields Collection

Filter Property

LockEdits Property

OpenRecordset Method

Populating Recordsets

Requery Method

Snapshot Object

Sort Property

Table Object

TableDef Object, TableDefs Collection

Updatable Property

Update Method


Snapshot-Type Recordset

See Also	Example	Properties	Methods

A snapshot-type Recordset object is a static set of records that you can use to examine data in an underlying table or tables.  A snapshot-type Recordset can contain fields from one or more tables in a database but can't be updated.

Remarks

When you create a snapshot-type Recordset, data values for all fields (except Memo and OLE Object field data types) are brought into memory.  Once loaded, changes made to base table data aren't reflected in the snapshot-type Recordset data.  To reload the snapshot-type Recordset with current data, use the Requery method, or re-execute the OpenRecordset method.

The order of snapshot-type Recordset data isn't guaranteed to follow any specific sequence.  To order your data, use an SQL statement with an ORDER BY clause to create the Recordset.  This technique can also be used to filter the records so that only certain records are added to the Recordset.  For example, the following code selects only titles whose name contains the string "VBSQL" and sorts the resulting records by ISBN:

Dim Db As Database, Rs As Recordset, SQL As String

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")

SQL$ = "SELECT * FROM Titles WHERE Title like '*VBSQL*' ORDER BY ISBN;"

Set Rs = Db.OpenRecordset(SQL$,dbOpenSnapshot)

Using this technique instead of the Filter or Sort properties or testing each record individually generally results in faster access to your data.

To create a snapshot-type Recordset, use the OpenRecordset on an open database, on another dynaset- or snapshot-type Recordset, or on a QueryDef object.

Snapshot-type Recordset objects are generally faster to create and access than dynaset-type Recordset objects because their records are either in memory or stored in TEMP disk space, and the Microsoft Jet database engine doesn't have to deal with page locking or multiuser issues.  However, snapshot-type Recordset objects consume more local resources than dynaset-type Recordset objects because the entire record is downloaded to local memory.


See Also

Activating Data Access Objects

Dynaset Object

Field Object, Fields Collection

OpenRecordset Method

Property Object, Properties Collection

Populating Recordsets

Requery Method

QueryDef Object, QueryDefs Collection

Snapshot Object

Table Object

TableDef Object, TableDefs Collection

Type Property


Snapshot-Type Recordset Example

This example creates a new snapshot-type Recordset object and opens it, appending it to the Recordsets collection in the default database.  It then finds a record and prints it.

Function ShowVBSQL () As Integer

Dim MyDB As Database, MyData As Recordset

Dim I As Integer, J As Integer

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set MyData = MyDB.OpenRecordset(Titles, dbOpenSnapshot)

If MyData.RecordCount > 0 Then

MyData.FindFirst "Title Like '*VBSQL*'"  ' Any title on VBSQL

Do until MyData.NoMatch = True

Debug.Print MyData!Title

MyData.FindNext "Title Like '*VBSQL*'"

Loop

Else

Debug.Print "No such title"

End If

MyData.Close

MyDb.Close

ShowVBSQL = True

End Function


Table-type Recordset

See Also	Example	Properties	Methods

A table-type Recordset object is a representation in code of a base table that you can use to add, change, or delete records from a table.  Only the current record is loaded into memory.  A predefined index is used to determine the order of the records in the Recordset object.

Remarks

To create a table-type Recordset, use the OpenRecordset method on an open Database object.

A table-type Recordset can be created with a Jet database base table but not with an ODBC or attached table.  The table-type Recordset can be used with ISAM databases (like FoxPro, dBASE, Paradox, or Btrieve) when opened directly.

Unlike dynaset- or snapshot-type Recordset objects, the table-type Recordset can't refer to more than one base table, and it can't be accessed using an SQL statement that filters or sorts the data.  Generally, when you access a table-type Recordset, you specify one of the predefined indexes for the table, which orders the data returned to your application.  If the table doesn't have an index, the order of the data returned can't be guaranteed.  If necessary, your application can create an index that returns records in a specific order.  To choose a specific order for your table-type Recordset, set the Index property to a valid index.

To maintain data integrity, table-type Recordset objects are locked during Edit and Update operations so that only one user can update a particular record at a time.  When the Microsoft Jet database engine locks a record, it locks the entire  2K page containing the record.

Two kinds of locking are used with non-ODBC tables [image] pessimistic and optimistic.  ODBC-accessed tables always use optimistic locking.  The locking conditions in effect during editing are determined by the LockEdits property.


See Also

Activating Data Access Objects

Dynaset Object

Edit Method

Field Object, Fields Collection

Index Object, Indexes Collection

LockEdits Property

OpenRecordset Method

Populating Recordsets

Snapshot Object

Table Object

TableDef Object, TableDefs Collection

Type Property

Updatable Property

Update Method


Table-Type Recordset Example

This example opens a table-type Recordset and selects an index for the Recordset.  By setting an index, the Microsoft Jet database engine returns records in the order specified by the index.  Without an index, table-type Recordset objects return records from the database table in no particular order.

Dim Db As Database

Dim MyTable as Recordset, MyIndex As Index

Dim I As Integer

' Get workspace and database.

Set Db = Workspaces(0).OpenDatabase("MyDB.MDB")

Set MyTable = Db.OpenRecordset("Titles", dbOpenTable)

MyTable.Index = "MyIndex"

.

.

.


Error Object, Errors Collection

See Also	Properties	Methods	Summary

Error object [image] contains details about data access errors.

Errors collection [image] contains all stored Error objects, each of which pertains to a single operation involving data access objects (DAO).

Remarks

Any operation involving data access objects can generate one or more errors.  As each error occurs, one or more Error objects are placed in the Errors collection of the DBEngine object.  When another DAO operation generates an error, the Errors collection is cleared, and the new Error object is placed in the Errors collection.  DAO operations that don't generate an error have no effect on the Errors collection.

Members of the Errors collection aren't appended as is typical with other collections.  The most general errors are placed at the end of the collection (Count -1), and the most detailed errors are placed at index 0.

The set of Error objects in the Errors collection describes one error.  The first Error object is the lowest level error, the second the next higher level, and so forth.  For example, if an ODBC error occurs while trying to open a Recordset object, the last Error object contains the DAO error indicating that the object couldn't be opened.  The first error object contains the lowest level ODBC error.  Subsequent errors contain the ODBC errors returned by the various layers of ODBC.  In this case, the driver manager, and possibly the driver itself return separate Error objects.

Note   If you use the New keyword to create an object that causes an error before or while being placed into the Errors collection, the collection doesn't contain error information about that object (it might contain information from a previous error).

The error information is available in the Err object.

To determine if the error information in the Errors collection is valid, compare the Number property of the last element of the Errors collection (DBEngine.Errors(DBEngine.Count-1)) with the Visual Basic Err value.


See Also

Dim Statement

DBEngine Object

Recordset Object


Error Object, Errors Collection Properties

Legend

Count

Description

HelpContext

HelpFile

Number

Source


Error Object, Errors Collection Methods

Legend

Refresh


Error Object, Errors Collection Summary

Error Object

An Error object contains these properties:

Properties

Description	Number

HelpContext	Source

HelpFile

Errors Collection

The Errors collection contains no methods and this property:

Property

Count


Choosing a Field Data Type

See Also

Every field in a table must have a defined data type.  Like Visual Basic data types, the Field object data type determines the kind and range of values that can be entered in a field, the amount of storage space available in the field, and the amount of space allocated in the database to store the data.

Don't confuse the variable data types used by Visual Basic with the data types used to describe database fields.  Choose a variable type best suited to contain the data used in the database.  Conversions are done automatically wherever possible.  Your code triggers a trappable error if you attempt to save a value that doesn't conform to the limitations of the field.

For Field objects declared as type dbText, you also need to set the Size property that indicates the length of the longest string to be saved in the field.  All other types of Field objects have their Size property set automatically.

The table below lists the types of data, the constant used in the Type property, and their uses.

Data	Constant	Use for

Text	dbText	Text and numbers, such as names and addresses, phone numbers and postal codes.  A Text field can contain from 0 to 255 characters.  You must set the Size property to the maximum length of your text when you declare a field as type Text.

Memo	dbMemo	Lengthy text and numbers, such as comments or explanations.  A Memo field can contain up to 1.2GB characters.

Number	(See below)	Numerical data on which you intend to perform mathematical calculations, except calculations involving money.  See the table below for a further explanation of number fields.

Date/Time	dbDate	Dates and times.  These values are stored in a combined field [image] the date is always stored with the time.  Note that all dates are stored in U.S. format.

Currency	dbCurrency	Used where a field contains monetary values.  Don't use the Number data type for currency values because numbers to the right of the decimal may be rounded off during calculations.  The Currency data type maintains a fixed number of digits to the right of the decimal.  Set the Field object Type property to dbCurrency for currency fields.

Counter	dbLong	Sequential numbers automatically inserted by the Microsoft Jet database engine.  Set the dbAutoIncrement flag in the Field object Attributes property.  Numbering begins with 1.  The Counter data type makes a good primary key field.  If you want to establish a primary key/foreign key relationship between two tables using a counter field, make sure that the foreign key column data type is also defined as Long.

Yes/No	dbBoolean	Yes/No, True/False, On/Off, or fields that contain only one of two Boolean values.

OLE Object	dbLongBinary	Objects created in other programs using the OLE protocol.  Managed by OLE, Image or PictureBox controls.

Binary Image	dbLongBinary	Any value that can be expressed in binary up to 1.2GB in size.  This type is used to store pictures, files or other raw binary data.  Managed by Image or PictureBox controls.

Number Types	Use for

dbBoolean	Binary values of 0 or 1.

dbByte	Positive values from 0 to 255.  Stored in Byte variables.

dbInteger	Values from -32,768 to +32,767.  Stored in Integer variables.

dbLong	-2,147,483,648 to 2,147,483,647 (about 2.1 GB).  Stored in Long variables.

dbSingle	-3.402823E38 to 1.401298E-45 for negative numbers and 1.401298E-45 to -3.402823E38.  Stored in Single variables.

dbDouble 	1.79769313486232E308 to 4.94065645841247E-324 for negative values and 4.94065645841247E-324 to 1.79769313486232E308 for positive values.  Stored in Double variables.

Notes

Select the appropriate data type for each field.  For example, you usually define most fields in a table of names and addresses as Text fields.  Even a phone number field that contains only digits should be defined as a Text field.  Reserve the Number data type for fields on which you want to perform calculations.  Note that the Variant data type can accept any of these types and also supports NULL values.

You can't index fields with the data types Long Binary, Memo or OLE Object.

Limitations

The records you define must fit on the 2K pages supported by the Jet engine.  Each Field you include in the table definition counts toward this 2K total, including Binary and Memo fields.  However, the amount stored for Binary and Memo fields is only 14 bytes per non-null field, and only 1 byte for null fields, as the actual data for these fields is stored on additional pages.  The amount of data committed to each text field isn't set until you actually store data in the field.  Generally, you can "overcommit" a data page by defining more text fields than there would be room for, but no more than about 2K of actual data can be stored in a record.  For example, you can define 15 250-byte text fields in a record as long as the total number of characters stored is less than about 2K.  See the definitions for each of the data types to find out how much space each type of field uses.


See Also

Field Object, Fields Collection

Parameter Object, Parameters Collection

Property Object, Properties Collection

Size Property

Type Property

Using Counter Fields


Using SQL PassThrough

See Also

SQL PassThrough permits your application to effectively bypass the Microsoft Jet database engine query processor and route foreign-dialect SQL statements to an external database server like SQL Server.

This technique is used to pass single or multiple SQL commands, stored procedures, or other SQL statements to an external database server to be executed.  Whenever you specify a SQL PassThrough query, the Jet database query processor is bypassed, but its recordset processor is used to create and manage the result sets that may be generated by your query.

Typical Uses

SQL PassThrough can be used to force query processing to be executed on an external database engine.  For example, you can use SQL PassThrough to:

Execute a stored procedure.

Run an SQL query using foreign syntax or return more than one set of results.

Create a new database, table or index on an external server.

Create or manage Triggers, Defaults, Rules or stored procedures.

Maintain user accounts or perform other System Administrator tasks.

Run maintenance operations like Microsoft SQL Server's DBCC.

Execute multiple INSERT or UPDATE statements in a single batch.

Implementation

Although the technique shown below uses the QueryDef object to store and execute the foreign-language SQL query, you can't set parameters for the query using the Parameters collection of the QueryDef object.  To build SQL queries that are created in code or require parameters, you need to construct or modify the query in code.

If there are result records (rows) from your SQL PassThrough query, the Jet engine creates a snapshot-type Recordset objects for each set of results.

This version of the Jet engine supports use of SQL Passthrough by permitting your code to set the SQL property of the QueryDef object to contain non-Jet engine SQL syntax.  Although you can still place foreign SQL syntax in the SQL argument of the CreateDynaset, CreateSnapshot or ExecuteSQL methods, and use the dbSQLPassThrough option, this outdated technique isn't recommend.

To create a SQL PassThrough QueryDef

1.	Use the CreateQueryDef method to create a QueryDef object using only a name argument.  If you specify an SQL argument, you can't use foreign SQL syntax [image] it must comply with Jet engine SQL syntax.  To create a temporary QueryDef that isn't automatically saved in the database, use the CreateQueryDef method without the name argument.

Note   The dbSQLPassThrough option doesn't need to be set by your code to execute a SQL PassThrough query using a Querydef object.  This option is set for you by the Jet engine.

2.	Set the Connect property of the QueryDef to a valid connect string to inform the Jet engine that this is a SQL PassThrough query.  From this point forward, the Jet engine doesn't attempt to parse the SQL property.

3.	Set the SQL property of the Querydef to the SQL statement to be executed.  Be sure to use SQL syntax as dictated by the external server.

4.	If you expect your query to return one or more sets of records (rows), set the ReturnsRecords property of the Querydef to True to inform the Jet engine to expect records (rows) back from the query.  This forces the Jet engine to create a Recordset for each set of results.  If you don't set the ReturnsRecords property to True for a query that returns records, a trappable error results.

For example, the following code creates a SQL PassThrough QueryDef that executes a stored procedure called MultipleResultSets:

Dim Rs As Recordset, Db As Database, Qd As Querydef

Set Db = Workspaces(0).OpenDatabase("MYDB.MDB")

Set Qd = Db.CreateQueryDef("My QD")

Qd.Connect = "odbc;dsn=MyDSN;uid=Chrissy;pwd=Champ;database=TestDB;"

Qd.SQL = "MultipleResultSets"

Qd.ReturnsRecords = True

To execute the SQL PassThrough QueryDef

1.	Use the OpenRecordset method to execute the stored Querydef so that the first (and only the first) set of results is available.

Set Rs = Db.OpenRecordset("My Qd", dbOpenSnapshot)

To process any additional result sets of a SQL PassThrough QueryDef

1.	 Create and execute a temporary QueryDef that executes a Jet SQL make table query using SELECT INTO syntax.  The Jet engine creates one new table for each set of results and stores them in your database.  If more than one user executes this code at the same time when using a shared database, the applications may generate table name collisions.

The SELECT INTO query doesn't return records, but it builds one or more tables to store the results from the QueryDef.  By not providing a name to the CreateQueryDef method, the Jet engine doesn't store a new QueryDef in the database.

Set Qd = Db.CreateQueryDef("")

Qd.SQL = "SELECT [My QD].* INTO Result FROM [My QD];"

Qd.Execute

2.	Create and process each of the resulting tables that contain the results of the QueryDef using the OpenRecordset method.

Set Rs = Db.OpenRecordset("Result")

' Process the results of the query...

3.	Repeat the process for each of the result sets.  Unless you know how many there are, you must query the TableDefs collection to see how many result set tables were created.  Note that the Jet engine numbers each subsequent table sequentially.  In this case, the table name Result contains the first set of results, Result1 contains the second and so on.

' Get second set of results.

Set Rs = Db.OpenRecordset("Result1")

' Process the results...

' Get Third set of results

Set Rs = Db.OpenRecordset("Result2")

' Process the results...

Rs.Close	' Close the Recordset, you are done with it.

4.	Remove the tables used to store the results of your query.

Db.Execute "Drop table [Result]"

Db.Execute "Drop table [Result1]"

Db.Execute "Drop table [Result2]"

To use SQL PassThrough with attached tables

1.	Open the database that contains the attached table.

Dim Db As Database

Set Db = Workspaces(0).OpenDatabase("ATTACHED.MDB")

2.	Set the Connect property of the attached tables Database object.

Db.Connect = "ODBC;DSN=SSRVR1;UID=Fred;PWD=RHS;DATABASE=SQLDB;"

3.	Create and execute the SQL PassThrough query using any of the methods described above.


See Also

Accessing External Databases

Building SQL Statements in Code

CreateQueryDef Method

Database Object, Databases Collection

DBEngine Object

Dynaset Object

Field Object, Fields Collection

Index Object, Indexes Collection

OpenRecordset Method

Parameter Object, Parameters Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

Workspace Object, Workspaces Collection


Using Counter Fields

See Also

In situations where your table records need a value to act as a unique record identifier, the Microsoft Jet database engine can be programmed to use a Counter field that automatically provides a unique value for this purpose.

To create a new Counter field with this feature, use Microsoft Access to specify a Counter data type.  If you use Visual Basic code, set the dbAutoIncrField bit in the Attributes property of a Field object, and assign the Long data type to the Type property.

Once enabled, the Jet engine automatically calculates a unique Long integer for this Field, and supplies it when the record is written to the table with the Update method.  Your code doesn't need to supply this value but if it does, the value must be a valid (and unique) Long integer >= 0.

To determine the number assigned once the data is written to disk, execute the Edit method, use the Requery method against the Recordset, or refresh the record from the table by repositioning to the LastModified property bookmark.  When your code establishes relationships to Counter fields, be sure to use the Long data type on related foreign key fields.


See Also

Attributes Property

Choosing a Field Data Type

Edit Method

Field Object, Fields Collection

LastModified Property

Recordset Object, Recordsets Collection

Type Property

Update Method


Examples of Converting Code to Jet Version 2.5/3.0

See Also

The Microsoft Jet database engine version 2.5/3.0 features a number of new objects, methods, and properties that can improve your existing applications.  The following examples demonstrate how to convert constructs in your existing applications that use Jet version 1.0, 1.1, or 2.0 to take advantage of these new features.  Note that, in virtually all cases, code written for Visual Basic version 2.5/3.0 runs unchanged with Visual Basic version 4.0.

Opening Databases

Version	Example

1.x	Set MyDb = OpenDatabase("BIBLIO.MDB")

2.5/3.0	Set MyDb = DBEngine.Workspaces(0).OpenDatabase("BIBLIO.MDB")

or	Set MyDb = Workspaces(0).OpenDatabase("BIBLIO.MDB")

or	Set MyDb = OpenDatabase("BIBLIO.MDB")

Opening a Table

Version	Example

1.x	Dim MyTable As Table
Set MyTable = MyDB.OpenTable("Titles")

2.5/3.0	Dim MyTable As Recordset
Set MyTable = MyDB.OpenRecordset("Titles", dbOpenTable)

or	Dim MyTable As Recordset
Set MyTable = MyDB!Titles.OpenRecordset()

Opening a Table Exclusively

Version	Example

1.x	Dim MyTable As Table
Set MyTable = MyDB.OpenTable("Titles", DB_DENYREAD)

2.5/3.0	Dim MyTable As Recordset
Set MyTable = MyDB.OpenRecordset("Titles", dbOpenTable, dbDenyRead)

or	Dim MyTable As Recordset
Set MyTable = MyDB!Titles.OpenRecordset(dbOpenTable, dbDenyRead)

Opening a Dynaset

Version	Example

1.x	Dim MyDynaset As Dynaset
Set MyDynaset = MyDB.CreateDynaset("Titles")

2.5/3.0	Dim MyDynaset As Recordset
Set MyDynaset = MyDB.OpenRecordset("Titles", dbOpenDynaset)

or	Set MyDynaset = MyDB!Titles.OpenRecordset(dbOpenDynaset)

Opening a Snapshot

Version	Example

1.x	Dim MySnapshot As Snapshot
Set MySnapshot = MyDB.CreateSnapshot("Titles")

2.5/3.0	Dim MySnapshot As Recordset
Set MySnapshot = MyDB.OpenRecordset("Titles", dbOpenSnapshot)

or	Set MySnapshot = MyDB!Titles.OpenRecordset(dbOpenSnapshot)

Listing Fields (Replaces ListFields Method)

Version	Example

1.x	' Given open Table object MyTable.
Dim ListSet As Snapshot
Set ListSet = MyTable.ListFields()
While Not ListSet.EOF
Debug.Print ListSet!Name, ListSet!Type
ListSet.MoveNext
Wend
ListSet.Close

or	' Given open Database object Db
Dim i%, j%, Td As TableDef
For j% = 0 To Db.TableDefs.Count - 1
Set Td = Db.TableDefs(j%)
Debug.Print "Table Name:"; Td.Name
For i = 0 To Td.Fields.Count - 1
Debug.Print Td.Fields(i).Name;
Debug.Print Td.Fields(i).Type
Next I
Next j%

2.5/3.0	' Given open Recordset object MyTable.
Dim Fld as Field
For Each Fld in MyTable.Fields
Debug.Print Fld.Name, Fld.Type
Next Fld

or	' Given table Table1 but no Table object.
Dim I As Integer, Dim DB As Database
Set DB = Workspaces(0).OpenDatabase("MyDb.MDB")
For I = 0 To DB!Table1.Fields.Count - 1
Debug.Print DB!Table1.Fields(I).Name
Next I

Listing Tables in a Database (Replaces ListTables Method)

Version	Example

1.x	' Given open Database object MyDB.
Dim ListSet As Snapshot
Set ListSet = MyDB.ListTables()
While Not ListSet.EOF
Debug.Print ListSet!Name
ListSet.MoveNext
Wend
ListSet.Close

or	' Given open Database object Db
Dim i%, j%, Td As TableDef
For j% = 0 To Db.TableDefs.Count - 1
Set Td = Db.TableDefs(j%)
Debug.Print "Table Name:"; Td.Name
Next j%

2.5/3.0	' Given open Database object MyDB.
Dim Td as TableDef
For Each Td in MyTable.TableDefs
Debug.Print Td.Name
Next Td

' Queries are in their own collection.
Dim J As Integer
For J = 0 To MyDB.QueryDefs.Count - 1
Debug.Print MyDB.QueryDefs(J).Name
Next J

Listing a Table's Indexes (Replaces ListIndexes Method)

Version	Example

1.x	' Given open Table object MyTable.
Dim ListSet As Snapshot
Set ListSet = MyTable.ListIndexes()
While Not ListSet.EOF
Debug.Print ListSet!Name
ListSet.MoveNext
Wend
ListSet.Close

or	' Given open Database object Db.
Dim i%, j%, Td As TableDef
For j% = 0 To Db.TableDefs.Count - 1
Set Td = Db.TableDefs(j%)
Debug.Print "Table Name:"; Td.Name
For i = 0 To Td.Indexes.Count - 1
Debug.Print Td.Indexes(i).Name;
Next I
Next j%

2.5/3.0	' Given open Recordset object MyTable.
Dim I As Integer, Idx as Index
For Each Idx in MyTable.Indexes
Debug.Print Idx.Name
Next I

Listing a Query's Parameters (Replaces ListParameters Method)

Version	Example

1.x	' Given open QueryDef object MyQuery.
Dim ListSet As Snapshot
Set ListSet = MyQuery.ListParameters()
While Not ListSet.EOF
Debug.Print ListSet!Name
ListSet.MoveNext
Wend
ListSet.Close

2.5/3.0	' Given open QueryDef object MyQuery.
Dim I As Integer, Qp as Parameter
For Each Qp in MyQuery.Parameters
Debug.Print Qp.Name
Next I

Setting Query Parameters Dynamically

Version	Example

1.x	' Given open Database Db.
Dim Qd as Querydef, Ds as Dynaset
Set Qd = Db.OpenQueryDef("MyQuery")
Qd.ParameterName = "parm"
Set Ds = Qd.CreateDynaset()

2.5/3.0	' Given open QueryDef object MyQuery.
Dim I As Integer
For I = 0 To MyQuery.Parameters.Count - 1
MyQuery.Parameters(I) = InputBox("Value for " & MyQuery.Parameters(I).Name)
Next I

or	Dim I As Integer
For I = 0 To MyQuery.Parameters.Count - 1
MyQuery.Parameters(I) = InputBox("Value for " & MyQuery(I).Name)
Next I

Running a Pass-Through Query

Version	Example

1.x	' Given an open database object MyDb.
Dim Rows as Long
Rows = MyDb.ExecuteSQL("EXECUTE SP_MySp")

or	Dim Sn as Snapshot
Set Sn = Db.CreateSnapshot("EXECUTE SP_MySp", DB_SQLPassThrough)

2.5/3.0	' Given open Database object MyDb.
Dim Q As QueryDef
Set Q = MyDb.CreateQueryDef("MYODbCQuery")
Q.Connect = "ODBC;" _
& "DSN=MyServer;" _
& "UID=sa;" _
& "PWD=hithere;" _
& "DATABASE=pubs"
Q.SQL = "Exec SP_MySp"
Q.ReturnsRows = True
...
Dim R As Recordset
Set R = Q.OpenRecordset()

Creating a Temporary Query

Version	Example

1.x	' Given open Database object MyDb.
Dim TempQ As QueryDef
Dim TempQName As String
TempQName = "TMP:" & User() & Time()
TempQ = MyDb.CreateQueryDef(TempQName)
TempQ.SQL = "Update Table1 Set Table1.Field1 = Field1 * 1.1;"
...
TempQ.Execute
TempQ.Close
...
MyDb.DeleteQueryDef(TempQName)

2.5/3.0	' Given open Database object MyDb.
Dim TempQ As QueryDef
Set TempQ = MyDb.CreateQueryDef("", "Update Table1 Set Table1.Field1 = Field1 * 1.1;")
...
TempQ.Execute
TempQ.Close


See Also

CreateQueryDef Method

Creating Parameter Queries

Database Object, Databases Collection

DBEngine Object

Dynaset Object

Field Object, Fields Collection

Index Object, Indexes Collection

OpenRecordset Method

Parameter Object, Parameters Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

Workspace Object, Workspaces Collection


Creating Parameter Queries

See Also

In situations where your application executes the same query repeatedly, it is more efficient to create a stored QueryDef object that contains the query SQL statement.  Queries stored in the database execute faster and can be used by anyone with access to the database.

If your application needs to alter WHERE clause arguments in a query, you can also add a PARAMETERS clause to your query that permits the Microsoft Jet database engine to substitute values into the query at run time.  Before running Parameter queries, your application must substitute values for each of the parameters as stored in the Parameters collection of the Querydef.

To create a parameter query

1.	Create a PARAMETERS clause string that includes a parametername and datatype for each parameter.  Don't use the field name alone as the parametername, because duplicating it may cause problems.  You can include the field name within the parametername, however.

If you are working with a database accessed by Microsoft Access, the parametername is used as a prompt string.  Keep this in mind if you expect Microsoft Access users to use this query.

Shown below is a typical PARAMETERS clause:

SQL$ = "PARAMETERS [Product Wanted] TEXT; [Size] LONG "

2.	Create a SELECT statement that fetches the needed fields and incorporates the named parameters into the WHERE clause.  In the example below, the parameters are used to filter the query to return only selected products of a specified size.  Note that the parameter [Product Wanted] is substituted by the Jet engine during execution of the query at run time.

SQL$ = SQL$ & "SELECT DISTINCTROW * " _ ' Add SELECT to PARAMETERS

& " FROM Vendors" _

& " WHERE ((Vendors.Product_ID =[Product Wanted]) " _

& " AND (Vendors.Size_= [Size])) " _

& " WITH OWNERACCESS OPTION; "

3.	Create a named QueryDef with your SQL statement.

Dim Qd as QueryDef

Set QD = CreateQueryDef("Find Vendors", SQL$)

4.	You are now ready to set the QueryDef parameters.  First, you need to gain access to the QueryDef.  You can either use the QueryDef object just created, or reference the stored QueryDef object from the QueryDefs collection.  The example shows two different types of addressing; either is acceptable.  You can also address the parameters by their ordinal number.

Dim ParmQD as QueryDef

Set ParmQD = MyDb.QueryDefs("Find Vendors")

ParmQD("Product Wanted") = "Salmon"	' Note the two ways to

ParmQD!Size = 16	' address the parameters.

5.	You are now ready to execute the procedure.  Because this query returns records, you need to create a Recordset to capture the result set.

Dim Rs as Recordset

Set Rs = ParmQD.OpenRecordset()

Note

You can use the BETWEEN...AND SQL operators in a parameter query to retrieve a range of values.  For example, you could enter BETWEEN [Low price] AND [High price] in the WHERE clause to fetch a list of products within a certain range of prices.

You can create a parameter query with the LIKE operator that allows the user to provide wildcard characters.  For example, if you entered LIKE [Enter the first letter]&*, the user could enter '"B" to display all values that start with the letter B.


See Also

LIKE Operator (SQL)

Parameter Object, Parameters Collection

PARAMETERS Declaration (SQL)

QueryDef Object, QueryDefs Collection

SELECT statement (SQL)

WHERE clause (SQL)


Populating Recordsets

See Also

This topic discusses how to accomplish recordset population and how it affects the performance and operation of your application.

Recordset objects are composed of zero or more database records (rows) that become part of the Recordset based on criteria you specify when you create the Recordset.  When the Microsoft Jet database engine adds a record to a Recordset, the record is considered a member of the Recordset object.

Determining Recordset Membership

Membership in Dynaset, dynaset-type Recordset (dynaset), Snapshot, or snapshot-type Recordset (snapshot) objects isn't fixed until the current row pointer is positioned to the last eligible row.  It is only then that the Recordset is considered to be fully populated.  To force immediate population, you can execute a MoveLast or FindLast method against the Recordset, or move the current record pointer to (that is, visit) each record in the Recordset.

In some cases, a Recordset may be fully populated immediately following its creation.  Depending on the way the Jet engine creates it, or how you phrase the SQL query, the number of populated rows can vary from a minimum of 0, when the Recordset is empty, to the total number of rows returned by the query.

In a multiuser environment, multiple users can add, delete or change records that make records qualify or disqualify as members of the Recordset until it is fully populated.  This means that any Recordset can contain records retrieved over a relatively long period of time.

Until you execute a MoveLast method, or otherwise position to the end of the Recordset, the number of qualified members in your Recordset can't be determined because it isn't fixed.  For this reason, the RecordCount property is set to zero for an empty Recordset or to the number of records actually fetched by the Jet engine.  Once you move the current record pointer to the last record, no further members are included, and the RecordCount property reflects the total number of records in the Recordset, regardless of the changes that other users make.  When working with Table objects, the RecordCount property of the TableDef object associated with the Table contains a current count of records in a specific table.

When other users delete records from the base table(s), your Recordset object's RecordCount property remains unchanged until you set the current record to the deleted record.  At this point you trigger a trappable error and the current record is no longer valid.  When your code positions to records changed by other users, these changes are available to your table-type and dynaset-type Recordset object, but not to your snapshot-type Recordset object .

When your code uses the MoveNext method, the Jet engine often fetches more than one record from the database to improve performance.  Because of this, the RecordCount can increase by more than one when you execute the MoveNext method or set the AbsolutePosition property.

Background Population

When you use a Data control to create a Recordset, or when a Recordset is created in code and passed to the Data control, the current record pointer isn't moved unless the user manipulates the Data control, or your code uses one of the reposition methods.  However, in the background, the Jet engine automatically populates your Recordset until the last record has been accessed.  This means that bookmarks, and in the case of snapshot-type Recordset objects, Recordset data, is saved in local memory without the user having to manipulate the Data control, or your code having to execute the MoveLast method.  It also means that page locks created to build the Recordset are released more quickly, making it possible for other Recordset objects to access the same data.

Background population of a Data control's Recordset objects doesn't apply to Recordset objects created in code but not passed to the Data control for processing.  In this case, you should use your own code to fully populate the Recordset as quickly as possible.

Determining Current Record Position

The PercentPosition and AbsolutePosition properties can be used to set or return the location of the current record relative to the RecordCount property value.  Setting the AbsolutePosition property to the current setting of the RecordCount property causes the Jet engine to fetch another block of records, which adds to the membership of the Recordset.  However, if the Recordset is fully populated, setting AbsolutePosition to RecordCount causes a trappable error.

When working with external ODBC databases that can only handle one active statement, the connection to the external server is held open until the Recordset is fully populated.  In addition, this connection can't be reused for other queries until the last result set is completely fetched.  For these reasons, your code should attempt to fully populate the Recordset as quickly as possible.  You shouldn't create applications that open Recordset objects for user browsing without first fully populating them.

Note that the Data control fully populates any Recordset objects it creates in the background so your code doesn't need to perform a MoveLast method to force population.


See Also

AbsolutePosition Property

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

PercentPosition Property

RecordCount Property

Recordset Object, Recordsets Collection

Using SQL PassThrough


Building SQL Statements in Code

See Also

This topic discusses how to create a Structured Query Language (SQL) Statement to manipulate data in your database.  SQL statements can be used to retrieve data from one or more tables, add, update or delete records, or execute stored procedures or foreign SQL statements on external databases.

Overview

To provide your application with the ability to generate context-sensitive SQL queries or adapt existing queries in ways not ordinarily supported by parameter queries, your application can build an SQL query in code.  Parameter queries can only accept SQL arguments that substitute for the values in the SQL statement but not table names, expressions or operators.

If you don't expect the Microsoft Jet database engine query to be changed by your code, create a permanent query in Microsoft Access or a QueryDef in your Visual Basic code.  QueryDef objects execute faster and can be executed by other applications that use your Jet engine database.  In many cases, you can create a parameter query that has all of the advantages of a QueryDef and also accepts parameters that can be substituted at run time.

Determine the SQL Dialect

To create an SQL statement in your application, first determine the target of the query.  If it is the Jet engine, you need to use Jet engine syntax.  Otherwise, use the syntax required by the backend processor.  If you are working with a database engine other than the Jet engine (like SQL Server), your only option to pass parameters to SQL statements or stored procedures may be to build the SQL statement in code.

When working with the Jet engine, the easiest way to create SQL statements is to use Microsoft Access to create a sample that closely approximates the syntax needed by your application.  Once the sample is created and tested, use the Clipboard to paste it into your Visual Basic application.

Construct the Query

When your application is ready to modify the SQL sample, use the concatenation operator (&) to join portions of the sample SQL with the contents of controls or variables in your application.  Avoid using the plus operator (+), which implies addition of the arguments.  If your substituted arguments must be bounded by quotes in the SQL query, your logic must provide quotes on both ends of the string.

Watch out for arguments passed from the user that contain single or double quotes, because these may break the quote pairing in your SQL statement.  You can use either single ( ' ) or double ( " ) quotes to frame quoted strings, as long as they are used in matched pairs.

For example, the following procedure accepts the name of a column to search and a search argument,  and inserts them into an SQL query.  The code then completes the SQL query based on the arguments, creates a Recordset and places the name field of the first selected publisher into a TextBox.

Sub FindPub (Db as Database, Column as String, Criteria as String)

Dim SQL as String, Rs as Recordset

SQL = "SELECT * FROM Publishers" _

& " WHERE " & Column & Criteria" _

& "'" & Publisher.Text & "'"

Set Rs = Db.OpenRecordset(SQL,dbOpenSnapshot)

If Rs.RecordCount <> 0 Then

FoundPublisher.Text = Rs(Name) & ""

Else

FoundPublisher.Text = "(Not found)"

End If

End Sub

If you call this procedure with "PUB_ID" as the column argument, " = " as the criteria argument and Publisher.Text contained "2774" , the SQL statement generated is:

SELECT * FROM Publishers WHERE PUB_ID = '2774'

Tip   Watch out for spaces before and after the arguments provided, especially when you break your string into more than one line.  Without the space before the WHERE clause, the SQL statement would read: SELECT * FROM Publishers WHERE....  Note that the code shown above uses the line continuation character.  This syntax is supported by Visual Basic to help break up longer lines, but isn't supported (or really necessary) with SQL statements.


See Also

QueryDef Object, QueryDefs Collection

Retrieving Data Using SQL


Using Named Arguments

See Also

In some cases, arguments for methods, functions, statements and procedures can be coded using the argument name instead of positional arguments.  This topic discusses how to write code for and pass these arguments.

Note   Named arguments aren't supported universally in Visual Basic.  If you aren't sure whether a method, function or statement supports named arguments, consult Help or the Object Browser on the specific topic.

Coding

Postional arguments are specified by coding arguments in a specific order.

Named arguments use the argument name followed by :=.  For example, to supply False to an argument named "READONLY", use: READONLY:=False.  Each named argument is listed in the object library under the method, function or statement.  Press F2 to open the object library dialog.

Using named arguments doesn't eliminate the need to specify arguments where required, but it does allow you to place them in any order.  Separate all arguments by commas, regardless of style.

To determine specific names to use for each argument, paste the object into your code from its object library entry.  For example, the entry for the OpenDatabase method appears as:

OpenDatabase(Name:=, [Exclusive]:=, [ReadOnly]:=, [Connect]:=)

Using positional arguments, the OpenDatabase method can be coded in a number of ways.  For example, where only the database name is supplied:

Set Db = OpenDatabase("MyDb.MDB")

Or, where the name, exclusive, readonly and connect arguments are all supplied:

Set Db = OpenDatabase("MyDSN", _

False, _

False , _

"ODBC;UID=Vicky")

The OpenDatabase method can also be coded by replacing positional arguments with equivalent named arguments.  For example, where only the database name is supplied:

Set Db = OpenDatabase(Name:="MyDb.MDB")

Or, where the name, exclusive, readonly and connect arguments are all supplied:

Set Db = OpenDatabase(Name:="MyDSN",  _

Exclusive:=False, _

ReadOnly:=False, _

Connect:="ODBC;UID=Vicky")

Or, where the name, exclusive, readonly and connect arguments are supplied, but in a different order:

Set Db = OpenDatabase(Connect:="ODBC;UID=Vicky, _

Name:="MyDSN",  _

ReadOnly:=False, _

Exclusive:=False")


See Also

Object Browser


Retrieving Data Using SQL

See Also

You can use SQL to query, update, and manage relational databases such as Microsoft Jet databases.

For some query types [image] such as pass-through, data-definition, and union queries [image] you must use an SQL statement.

You can also use SQL statements in many places where you can enter the name of a table, query, or field.  For example, you can enter an SQL statement instead of a table name when using the OpenRecordset method to create a Recordset object.

To learn more about the parts of an SQL statement, search Help for any of the Microsoft Jet database engine SQL reserved words:

SELECT fieldlist

FROM tablenames IN databasename

WHERE searchconditions

GROUP BY fieldlist

HAVING searchconditions

ORDER BY fieldlist

SQL statements can't be entered in the same way as other Visual Basic commands.  To use an SQL statement in your program, build a string containing the statement and either include it as a literal quoted argument, or as a variable in a method, statement, or function.

Because SQL statements can be very long, you may wish to break them up for readability.  To do this, use the line continuation character ( _) as shown below.  Note that SQL statements can't contain imbedded carriage return characters, because these act as statement terminators.  The following example uses a valid SQL statement:

Dim SQL as String, Rst as Recordset

SQL$ = "SELECT [Last Name], [First Name] " _

& " FROM Employees " _

& " WHERE Salary > 21000;"

Set Rst = OpenRecordset(SQL$)

Note   You may want to use Microsoft Access to create queries for your Visual Basic application.  When you create a query in the Query window, Microsoft Access creates the equivalent SQL statement.  You can view or edit this statement by choosing SQL from the View menu in the Microsoft Access Query window or by clicking the SQL View button.  After Microsoft Access creates the SQL query, you can use the Clipboard to copy the query into your program or access the query using the stored QueryDef object.


See Also

DELETE Statement (SQL)

FROM Clause (SQL)

GROUP BY Clause (SQL)

HAVING Clause (SQL)

IN Clause (SQL)

INSERT INTO Statement (SQL)

Microsoft Jet Database Engine SQL Reserved Words

ORDER BY Clause (SQL)

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

UNION Operation (SQL)

UPDATE Statement (SQL)

Using SQL PassThrough

WHERE Clause (SQL)


Accessing Databases on CD-ROM

See Also

If you need to provide users with a Microsoft Jet database on CD-ROM or other read-only media, the CD-ROM must contain both the .MDB database file and the .LDB page lock file.  In addition, the database should be opened using the read-only and exclusive options.  By using the exclusive option, the Jet engine doesn't attempt to open the locking file.  Other users can still access the CD-ROM in the same way.


See Also

Database Object, Databases Collection

OpenDatabase Method

Opening a Database with the Data Control


Accessing Data in a Text Document

See Also

You can either attach or directly open text files, which can be stored in either fixed-width or delimited format.  The procedures for retrieving the data in text files are similar to those used to access data in other external data sources.  However, unlike other database types, text databases have no standard schema or structure that you can determine by inspection.  For this reason, you need to create a SCHEMA.INI that describes your text file database so that the ISAM driver can manipulate the data.

Generally, the ability to access text files is provided so you can import existing text files into your Microsoft Jet database or to export Jet or other attached database tables to text files.  You shouldn't access text files in order to establish attached text databases that can be simultaneously accessed like other attached database tables.

Special Caveats for Using Text Files

A text file can only be opened for a single user, because the Jet engine doesn't support multiple users of text files.  When referencing a text file, you must work with the entire file; you can't reference single fields or records within the file.

You can read both delimited and fixed-width text files.  The Jet engine recognizes commas, tabs, and custom delimiters when dealing with delimited text data, but you must use the same delimiter consistently.  Null data is denoted by two consecutive delimiters.  For example, if your delimiter is a double quote ("), two double quotes ("") denotes a Null value.  If you are using fixed-width data, you can specify the format of the data in a SCHEMA.INI file (see below).  Null fixed-width data is represented as spaces.

Tables are limited to a maximum of 256 columns.  Column names are limited to 64 characters, and column widths are limited to 65,500 characters.  Rows are limited to 65,543 bytes.

Attaching a Text File

To attach a text file as a table in your Jet database, use the OpenDatabase method to identify the location of your .MDB database and set the TableDef object to specify the location of the text file.  The following example shows how to attach an external text file:

Dim CurrentDatabase As Database

Dim MyTableDef As TableDef

'Open Microsoft Jet database named MYDB.MDB.

Set CurrentDatabase = OpenDatabase("C:\DATABASES\MYDB.MDB")

'Create TableDef.

Set MyTableDef = CurrentDatabase.CreateTableDef("MONTHS")

'Set connection information.

MyTableDef.Connect = "Text;Database=C:\TEXT\DATA\"

MyTableDef.SourceTableName = "MONTHS"

'Append TableDef to create link.

CurrentDatabase.TableDefs.Append MyTableDef

Opening a Text File

If you want to use table-type Recordset with your text file, you must open the file directly using the OpenDatabase method.  The following example shows how to directly open an external text file and create a Recordset object from the table:

Dim CurrentDatabase As Database

Dim MySet As Recordset

'Open external text data file.

Set CurrentDatabase = OpenDatabase("C:\TEXT\DATA",  _

  False, False, "Text;")

'Create Recordset from Awards table.

Set MySet = CurrentDatabase.OpenRecordset("MONTHS")

Customizing your .INI File

You must customize your .INI file to include the [Text ISAM] heading and the type of text file.  The .INI filename you use is set by the DBEngine INIPath property. The information entered into this section initializes the settings for the MSTX2016.DLL driver.  The following is an example of the heading and settings in the .INI file:

[Text ISAM]

Extensions=none,asc,csv,tab,txt

ColNameHeader=False

Format=TabDelimited

MaxScanRows=25

CharacterSet=OEM

Heading	Use for

Extensions	The name of the file extension for the text file.

ColNameHeader	True or False, indicating whether the first record of data is used for the column names.  Yes or no indicator.  Yes indicates that the first row of the table contains column names; during export column names are exported as the first row.  No indicates no column names in the first row; column names appear as numbers (1, 2, 3, and so on).

Format	TabDelimited, CSVDelimited, Delimited(<single character >), or FixedLength.  The single-character delimiter in the Delimited format can be any single character except a double quote (").

MaxScanRows	Number of rows to be scanned when guessing the column types.  If set to 0, the entire file is searched.

CharacterSet	OEM or ANSI, indicating whether the source file is written using an OEM or ANSI code page.

Customizing the SCHEMA.INI File

To import or export text data, you need to create a SCHEMA.INI file in addition to including the Text ISAM information in the .INI file.  SCHEMA.INI contains the specifics of a text data source: how the text file is formatted, how it is read at import time, and the default export format for files.  The following examples show the layout for a fixed-width file, FILENAME.TXT:

[FILENAME.TXT]

ColNameHeader=False

Format=FixedLength

MaxScanRows=25

CharacterSet=OEM

Col1=columnname Char Width 24

Col2=columnname2 Date(dd.mmm.yy) Width 9

Col3=columnname3 Date (mm-dd-yy) Width 8

Col4=columnname4 Date (mmm.dd.yy) Width 9

Col5=columnname5 Date (yyyy-mm-dd) Width 10

Col6=columnname6 Date (yyyy-mmm-dd) Width 11

Col7=columnname7 Float Width 10

Col8=columnname8 Integer Width 10

Col9=columnname9 LongChar Width 10

Similarly, the format for a delimited file is specified as:

[DELIMIT.TXT]

ColNameHeader=True

Format=Delimited(!)

MaxScanRows=0

CharacterSet=OEM

Col1=username char width 50

Col2=dateofbirth Date (dd-mmm-yy) width 9

If you are exporting data into a delimited text file, specify the format for that file as well:

[Export: My Special Export]

ColNameHeader=True

Format=TabDelimited

MaxScanRows=25

CharacterSet=OEM

DateTimeFormat=mm.dd.yy:hh.mm.ss

CurrencySymbol=Dm

CurrencyFormat=0

CurrencyDigits=2

CurrencyNegativeFormat=0

DecimalSymbol=,

NumberDigits=2

NumberLeadingZeros=0

The FILENAME.TXT and DELIMIT.TXT examples above represent text files specified at setup time.  The My Special Export example refers to a specific export option; you can specify any variation of export options at connect time.  This last example also corresponds to a data source name (DSN) that can be optionally passed at connect time.  All three format sections can be included in the same .INI file.

The Jet engine uses the SCHEMA.INI entries as follows.

Entry	Description

ColNameHeader	Can be set to either True (indicating that the first record of data specifies the column names) or False.

Format	Can be set to one of the following values:  TabDelimited, CSVDelimited, Delimited(<single character delimiter), or FixedLength.  The delimiter specified for the Delimited file format can be any single character except a double quotation mark (").

MaxScanRows	Indicates the number of rows to be scanned when guessing the column data types.  If this is set to 0, the entire file is searched.

CharacterSet	Can be set to OEM or ANSI, indicating whether the source file is written using an OEM or ANSI code page.

DateTimeFormat	Can be set to a format string indicating dates and times.  This entry should be specified if all date/time fields in the import/export are handled with the same format.  All of the Jet engine formats except AM and PM are supported.  In the absence of a format string, the Control Panel short date picture and time options is used.

CurrencySymbol	Indicates the currency symbol to be used for currency values in the text file.  Examples include the dollar sign or Dm.  If this entry is absent, the default value in the Control Panel is used.

CurrencyFormat	Can be set to any of the following values:

0: Currency symbol prefix with no separation ($1)
1: Currency symbol suffix with no separation (1$)
2: Currency symbol prefix with one character separation ($ 1)
3: Currency symbol suffix with one character separation (1 $)

If this entry is absent, the default value in the Control Panel is used.

CurrencyDigits	Specifies the number of digits used for the fractional part of a currency amount.  If this entry is absent, the default value in the Control Panel is used.

CurrencyNegativeFormat	Can be one of the following values:

0: ($1)
1: $1
2: $1
3: $1
4: (1$)
5: 1$
6: 1$
7: 1$
8: 1 $
9: $ 1
10: 1 $
11: $ 1
12: $ 1
13: 1 $
14: ($ 1)
15: (1 $)

The dollar sign is shown for purposes of this example, but it should be replaced with the appropriate CurrencySymbol value in the actual program.  If this entry is absent, the default value in the Control Panel is used.

DecimalSymbol	Can be set to any single character that is used to separate the integer from the fractional part of a number.  If this entry is absent, the default value in the Control Panel is used.

NumberDigits	Indicates the number of decimal digits in the fractional portion of a number.  If this entry is absent, the default value in the Control Panel is used.

NumberLeadingZeros	Specifies whether a decimal value less than 1 and greater than  1 should contain leading zeros; this value can either be 0 (no leading zeros) or 1.

Col1, Col2, ...	Lists the columns in the text file to be read.  The format of this entry should be:

Coln=columnName type [Width #]

columnName: Column names with embedded spaces should be enclosed in quotation marks.

type: Can be Bit, Byte, Short, Long, Currency, Single, Double, DateTime, Text, or Memo.

In addition, the following ODBC Text Driver types are supported:

Char (same as Text)
Float (same as Double)
Integer (same as Short)
LongChar (same as Memo)
Date date format

The Width parameter is ignored if the Format entry is set to any of the delimited options.


See Also

Accessing Data in an Microsoft Excel Worksheet or Workbook

Accessing External Databases


Using the MSysConf Table With SQL Databases

See Also

If you are administering an SQL database with front-end applications that use the Microsoft Jet database engine, you can create a table in your SQL database named MSysConf to help you control communication between the two applications.  You can add this table to each SQL database you expect to access.  Without the MSysConf table in your SQL database, the Jet engine uses all of the default settings as described below.

The MSysConf table has two potential functions:

It can disable the feature that enables users to store the login ID and password for an attached SQL database locally.

It can optimize how the Jet engine performs background population of records during idle time when using the Data control.  Using the MsysConf table, you can set the number of rows of data that are retrieved at one time and the number of seconds of delay between each retrieval.  The Jet engine uses a default of 100 records returned every 10 seconds if you don't create the MSysConf table.

The Structure of the MSysConf Table

The SQL database table MSysConf should have the following structure:

Column name	Data type	Allows Null?
Config	A data type that corresponds to a 2-byte integer	No
chValue	VARCHAR(255)	Yes
nValue	A data type that corresponds to a 4-byte integer	Yes
Comments	VARCHAR(255)	Yes
Note   If the data source you're working with is case-sensitive, use the table and column names exactly as shown.

All users must have permission to use the SELECT statement on this table, and only the system administrator should have INSERT/UPDATE/DELETE permission.

The Data in the MSysConf Table

There are three valid records in the MSysConf table.  The table below shows what values you should enter in the Config and nValue field.  The other columns are reserved for future use, and their contents are ignored.

Config	nValue	Meaning

101	0	Don't allow local storage of the login ID and password in attachments.

101	1 	(Default)  Allow local storage of the login ID and password in attachments.

102	D	D is the delay in seconds between each retrieval (default: 10 seconds).

103	N	N is the number of rows retrieved (default: 100 rows).

Notes

Setting a higher delay time decreases network traffic, but increases the amount of time that read-locks are left on data (if the server uses read-locks).

If you create an MSysConf table, it must be set up properly or you can't connect to the SQL database table at all.


See Also

Accessing External Databases


Positioning the Current Record Pointer

See Also

Whenever you work with Recordset objects, the record which can be examined or modified is referred to as the current record.  Although some bound controls permit you to show more than one record at a time, there is still only one current record available for modification.  This topic discusses how to position the current record pointer to specific records in an open Recordset.  For more detailed information, search Help for the individual methods or see the See Also list.

Unless you are using the Data control to position the current record pointer, you need to use one of the programmatic methods discussed below to reposition the pointer.  In some cases, no current record exists and references to it trigger a trappable error.  For example, the current record is invalid if you:

Delete the current record or all records in a Recordset.

Create a Recordset with no records.

Move beyond the beginning (BOF) or end (EOF) of the Recordset.

A Seek or Find has failed and the NoMatch property is True.

There are basically five ways to position the current record.  All of these techniques depend on the type of Recordset you are using, whether or not bookmarks are supported, and if the Recordset has a valid index.  See the table shown below to determine which methods work with which type of Recordset.

Manipulate the Data Control

Using the buttons on the Data control, you can move to the first, next, previous, and last record of a Recordset.  Once positioned at either end of the Recordset, further attempts to move off the end are ignored depending on the EOFAction and BOFAction properties of the Data control.

The Move Methods

The Move methods (MoveFirst, MoveLast, MovePrevious, MoveNext) reposition the current record pointer based on its current position (MoveNext and MovePrevious) or based on the beginning (MoveFirst) or end (MoveLast) of the Recordset.  Using the Move methods, you can position the current record pointer beyond either end of the Recordset, making it invalid.

Search Based on Criteria

Use the Seek method or one of the Find methods (FindFirst, FindLast, FindNext, FindPrevious) to reposition based on criteria you provide.  The Seek method works only with table-type Recordset objects, while the Find methods work only with dynaset and snapshot-type Recordset objects.  If the record you are searching for doesn't exist, the NoMatch property is set to True and the current record is invalid.

Using a Bookmark

If the Recordset you are working with supports bookmarks, you can move the current record pointer to any specific record by setting the Recordset object's Bookmark property to a valid bookmark.  To position to the record most recently added or changed, use the bookmark in the Recordset object's LastModified property.  If you clone a working Recordset, you can use bookmarks from the clone to position the current record pointer in the working Recordset.  The Move method can also be used to position based on a bookmark plus or minus an offset from that position.

Using Record Numbers

Although relational database applications shouldn't depend on record numbers, there are several methods that permit positioning within a Recordset based on the ordinal number of the record.  Note that a record number isn't assigned to individual records in the database, but is created when a Recordset is built.  For this reason, they can be different each time the Recordset is created.  Ordinal record numbers are assigned from 1 to RecordCount.

You can use the AbsolutePosition method to position to a specific record based on its ordinal number, or the PercentPosition method to move to the record closest to the percentage value provided.  For example, in a Recordset with 50 records, using the PercentPosition method with an argument of 10 positions to the 5th record.

Note that the Recordset object's RecordCount property for table-type Recordset objects is set to the number of records in the table.  For dynaset and snapshot-type Recordset objects, the RecordCount property is set to 0 for empty Recordset objects or to 1 for unpopulated Recordset objects.  As you move the current record pointer toward the end of the Recordset, the RecordCount property is incremented for each record visited.  Using the MoveLast method on the Recordset or its clone fully populates the Recordset and sets the RecordCount property to the number of records in the Recordset.

Background Population

When you use a Data control to create a Recordset, or when a Recordset is created in code and passed to the Data control, the current record pointer isn't moved unless the user manipulates the Data control or your code uses one of the reposition methods.  However, in the background, the Microsoft Jet database engine automaticallypopulates your Recordset  until the last record has been accessed.  This means that bookmarks, and in the case of snapshot-type Recordset objects, recordset data, is saved in local memory without the user having to manipulate the Data control, or your code having to execute the MoveLast method.  It also means that page locks created to build the Recordset are released more quickly, making it possible for other Recordset objects to access the same data.

Background population of Data  control Recordsets doesn't apply to Recordsets created in code but not passed to the Data control for processing.  In this case, you should use your own code to fully populate the Recordset  as quickly as possible.  In many cases, if you use the Clone method to create a duplicate of your Recordset, you can fully populate both recordsets by executing a MoveLast method on the clone.

Adding and Deleting Records

Records are always added to the end of the Recordset regardless of the order in which the Recordset was originally created.  After a record is added, the current record pointer is repositioned to the record that was current before the record was added.  When you need to delete records, only the current record can be deleted.  Once the delete is complete, the current record is invalid so you need to reposition it to another valid record.

Applying Reposition Methods

Method	Recordset	Notes
AddNew	Table-type, dynaset-type, Dynaset, Table	If Updatable property is True.
Delete	Table-type, dynaset-type, Dynaset, Table	If Updatable property is True.
Find methods	Dynaset-type, snapshot-type Dynaset, Snapshot	Current record is invalid if NoMatch is True.
Move	Dynaset-type, snapshot-type, table-type	Relative to current location or specific bookmark.
Move methods	Dynaset-type, snapshot-type, table-type, Dynaset, Snapshot, Table	Can reposition past EOF or BOF, making current record invalid.
PercentPosition	Dynaset-type, snapshot-type, table-type	Not for forward-only scrolling snapshots.
Seek	Table-type, Table	Current record is invalid if NoMatch is True.


See Also

AbsolutePosition Property

AddNew Method

Data Control

Delete Method

Dynaset-type Recordset

FindFirst, FindLast, FindNext, FindPrevious Methods

Move Method

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

NoMatch Property

PercentPosition Property

Populating Recordsets

RecordCount Property

Recordset Object, Recordsets Collection

Seek Method

Snapshot-type Recordset

Table-type Recordset


Customizing Data Access .INI Settings

See Also

Unless your application can work correctly with the default functionality of the Microsoft Jet database engine, you must create an initialization file that the Jet engine can access.  Unlike in Visual Basic version 3.0, the VB.INI file isn't searched for these initialization parameters.  Initialization entries are also used to tune the operation of the installable ISAM and ODBC drivers.  All of these parameters are expected to be kept in your initialization (.INI) file.  If your application can't accept the default behavior of the drivers, you must include appropriate parameters in your initialization file and point to this file using the INIPath property.

This initialization file is usually kept in the \WINDOWS directory and should be named based on the name of your application.  For example, if you have an application named "SOCCER.EXE" your application's .INI file would be named "SOCCER.INI".  This file is referred to as your <appname>.INI.

You can name this initialization file anything you choose and locate it anywhere on your system by setting the INIPath property of the DBEngine object to a specific path and filename.  You must set the INIPath property before the DBEngine is initialized by the first reference to any data access object.  This includes the Data control and any of the data access methods.  For example, the following code tells the Jet engine to use the MYAPP.INI file located at D:\MYDIR:

DBEngine.INIPath = "D:\MYDIR\MYAPP.INI"

To restart the DBEngine so you can reestablish initialization settings, you can code the following.  Note, however, that this operation closes all Database and Recordset objects.

DBEngine = Nothing

You can customize the settings of the .INI file as described below by using Windows Notepad or another text editor.  The revised settings take effect the next time you start your application.

Note   In Visual Basic version 3.0, path names indicating the location of the installable ISAM drivers are maintained in the <APPNAME>.INI file.  In Visual Basic version 4.0, these entries are automatically installed and maintained in the Windows registration database.

You can add entries to <APPNAME>.INI or revise existing entries to specify:

The file that defines your or your workgroup's system database (typically the SYSTEM.MDW file).  See Changing the System Database.

Settings used for interaction with Microsoft FoxPro, Paradox, and dBASE databases.  See Changing Paradox Database Settings, Changing Microsoft Foxpro Database Settings, and Changing dBASE Database Settings.

Settings used by Microsoft ODBC for interaction with SQL databases.  See Changing Microsoft ODBC Settings.

Settings that affect how the Jet engine reads and saves data.  See Changing Microsoft Jet Engine ISAM settings.

Settings that determine whether OLE links are saved in the OLE version 2.0 or OLE version 1.0 format.  See Specifying OLE Links Format.


See Also

DBEngine Object

Idle Method

INIPath Property


Changing the System Database

See Also

Use the following procedure to change the setting of the SystemDB option in the [Options] section of <APPNAME>.INI.

1.	Type the name and new path of the system database (typically, the SYSTEM.MDW file); for example:

SystemDB=C:\WRKGRP\SYSTEM.MDW

The next time you start the Microsoft Jet database engine, it uses the system database, SYSTEM.MDW, in the WRKGRP directory on drive C, including its security settings.

2.	Save your changes, exit your text editor, and start an application using the Jet engine.


See Also

Activating Security

Customizing Data Access .INI Settings


Changing Microsoft Jet Engine ISAM Settings

See Also

Use the following procedure to change the [ISAM] section of <APPNAME>.INI.  This section determines how data is read and saved.

1.	Change the setting of any of the following options:

Option	Description	Example
PageTimeout	Sets the length of time between when data that isn't being used is placed in an internal cache and when it's marked to be refreshed.  The settings are expressed in 100 millisecond units.  The default is 5 (500 milliseconds, or 0.5 seconds).	PageTimeout=5
LockedPageTimeout	Sets the length of time between when data that is being used is placed in an internal cache and when it's marked to be refreshed.  The settings are expressed in milliseconds.   The default is 5 (500 milliseconds, or 0.5 seconds).	LockedPageTimeout=5
CursorTimeout	Sets the cursor time-out in 1/10 second intervals.  The default is 5 (or 0.5 seconds).	CursorTimeout=5
LockRetry	Specifies the number of times to repeat attempts to access a locked page.   The default is 20.	LockRetry=20
CommitLockRetry	Specifies the number of times the Microsoft Jet database engine attempts to get a lock on data in order to save changes to data.  If it fails to get a commit lock, then updates are unsuccessful. The number of attempts the Jet engine makes to get a commit lock is directly related to the LockRetry entry.  For each attempt at getting a commit lock, it tries the number of times specified in the LockRetry setting to get a lock.  For example, if CommitLockRetry is 20 and LockRetry is 20, the Jet engine attempts to get a commit lock as many as 20 times, and for each of those times it tries to get a lock as many as 20 times, for a total of 400 attempts at locking. The default is 20.	CommitLockRetry=20
MaxBufferSize	The size of the Jet engine internal cache, measured in kilobytes (K).  MaxBufferSize must be between 18 and 4096.   Increasing this setting may provide better ODBC performance in systems with enough memory. The default is 512.	MaxBufferSize=512
ReadAheadPages	Sets the number of pages to read ahead when doing sequential scans.   The default is 16.	ReadAheadPages=16
2.	Save your changes, exit your text editor, and start an application using the Jet engine.


See Also

Customizing Data Access .INI Settings


Specifying the OLE Link Format

See Also

Use the following procedure to change the [Options] section of <APPNAME>.INI.  This section determines whether OLE links are saved in OLE version 1.0 or 2.0 format.

1.	Change the setting of any the following options:

Option	Description	Example
AllowOLE1LinkFormat	Specifies whether the Microsoft Jet database engine saves OLE links in OLE version 2.0 format, saving both relative and absolute link source references, or in OLE version 1.0 format, saving only absolute references. Set this option to 1 to ensure consistency of OLE linking operations in the Jet engine version 1.x databases in an environment where both the Jet engine version 2.0 and version 1.x are used. Valid settings: 0 (OLE version 2.0 link format) or 1 (OLE version 1.0 link format).  The default is 0.	AllowOLE1LinkFormat=0
2.	Save your changes, exit your text editor, and start an application using the Jet engine.


See Also

Customizing Data Access .INI Settings


Managing Connections to ODBC Data Sources

See Also

When you use the Microsoft Jet database engine to connect to ODBC data sources like SQL Server, the Jet engine opens one or more connections to the backend server.  These connections pass queries to the server and return result sets.  In Visual Basic version 3.0, the Jet engine automatically closed unused connections after 600 seconds (10 minutes).  In Visual Basic version 4.0, these connections remain open, even if your code closes the Recordset and Database objects, unless your code calls the Idle method of the DBEngine object after the time-out period expires.

To specify how much time the Jet engine waits before closing a connection, set the ConnectionTimeout parameter in your .INI file.  The name of the .INI file is determined by the INIPath property of the DBEngine object.  You must set this parameter before the Jet engine is initialized for it to have any affect.

To restart the DBEngine so you can reestablish initialization settings, use the following code.  Note, however, that this operation closes all Database and Recordset objects.

DBEngine = Nothing

To establish a connection time-out value

Use a text editor to set the ConnectionTimeout parameter in your .INI file to n (seconds).

Set the INIPath property of the DBEngine object to point to your .INI file before the Jet engine is initialized.  Generally, this must be done in the first Form_Load procedure before any references are made to data access objects.

Open a Database and create one or more Recordset objects.

When you are finished with the Recordset and Database objects:

Use the Close method to release the Recordset and Database object resources.

Wait for at least n seconds (the number of seconds set by the ConnectionTimeout parameter).

Call the Idle method of the DBEngine object.  This closes unneeded connections.

You may wish to set up a timer event in your Visual Basic application that periodically calls the Idle method to ensure that the Jet engine has enough time to complete background processing and to close unneeded connections as they time out.


See Also

Close Method

Customizing Data Access .INI Settings

Database Object, Databases Collection

DBEngine Object

IniPath Property


Using Bookmarks With the Microsoft Jet Version 2.5/3.0 Engine

See Also	Example

In Visual Basic version 3.0, the Bookmark property is managed as a String or Variant data type.  In Visual Basic version 4.0, the Bookmark property is managed as a Byte array.  For this reason, if you try to use the Bookmark property in a compare operation, a trappable error results.  For example, if you use the Bookmark property in a Select Case or If...Then...Else statement, a Type Mismatch error occurs because Visual Basic can't compare Byte arrays with any other variable type.

To compare bookmark values, copy them to string variables and write the comparison expression using these string variables.


See Also

Bookmark Property

Byte Data Type

If...Then...Else Statement

SelectCase Statement


Using Bookmarks With the Microsoft Jet Version 2.5/3.0 Engine Example

This example compares bookmarks in two Recordset objects:

Dim Db as Database

Set Db = OpenDatabase("BIBLIO.MDB")

Dim Book1 as String, Book2 as String

Dim Rs1 as Recordset, Rs2 as Recordset

Set Rs1 = Db.OpenRecordset("Titles")

Set Rs2 = Rs1.Clone()

Book1 = Rs1.Bookmark

Book2 = Rs2.Bookmark

If Book1 = Book2 Then Print "This comparison is valid"


Using Microsoft Jet Version 3.0 and 2.5

See Also

Visual Basic version 4.0 comes with two separate versions of the Microsoft Jet database engine:

Version 3.0 for 32-bit applications

Version 2.5 for 16-bit applications

Fortunately, the objects, properties, and methods of both versions are practically identical, making it easy to write database programs that can be compiled as both 16- and 32-bit applications with few, if any, changes to your code.

The two versions are highly compatible.  However, version 3.0 uses a slightly different database file format, and you will need to take this into consideration when creating a new database.  The important issues to understand are:

1.	Jet version 3.0 can use either version 2.5 or version 3.0 database files.

2.	Jet version 2.5 cannot use version 3.0 database files.

With these constraints in mind, you should always create version 2.5 databases if you want to create both 16- and 32-bit applications that use the same database.  Create version 3.0 databases if your applications will be 32-bit only.

How to Specify the Database Version

If you don't specify which database version to create, the Jet engine will automatically create a version 2.5 database if you are currently running 16-bit Visual Basic, and a version 3.0 database if you are running 32-bit Visual Basic.  You can explicitly modify this behavior by using the dbVersion constant in the CreateDatabase method.

Before you can use any Data Access Objects, you must make sure that the appropriate Type Library is referenced.  In the References dialog box available on the Tools menu, you will see the following available references:

Microsoft DAO 2.5 Object Library

Microsoft DAO 2.5/3.0 Compatible Library

Microsoft DAO 3.0 Object Library

For 16-bit applications, check the Microsoft DAO 2.5 Object Library.

For 32-bit applications, the Microsoft DAO 2.5/3.0 Compatible Library provides backward compatibility with older versions of DAO, allowing you to recompile existing Visual Basic version 3.0 code (Jet version 1.1) for 32-bit applications.

However, in future versions of Visual Basic, some of these older properties, methods, and objects will not be supported.  Therefore, to help you move to the new Jet 3.0 model and ensure that your existing code will continue to run properly, you should check the DAO 3.0 Object Library for new projects.  This library contains only the new DAO functionality.  Using this library ensures that new projects will continue to function correctly in future versions of Visual Basic (post Visual Basic 4.0).


See Also

CreateDatabase Method

Obsolete Features in DAO


Accessing External Databases

See Also

Your application can access data from external databases, which can include other Microsoft Jet databases (.MDB), ODBC-based databases, or installable ISAM databases.

The most efficient way to access external data is to attach an external table to an existing Microsoft Jet database.  Attaching a table creates a reference to the external table and saves it in your Jet database.  This stored link keeps a record of the database table's structure.  None of the external database data is stored in the .MDB file.

You can create dynaset-type and snapshot-type Recordset objects with attached tables.

To Attach tables to an existing Jet engine database

1.	Create variables for the Database and TableDef objects you are going to modify:

Dim tdf As TableDef, dbs As Database

2.	Use the OpenDatabase method to open the existing database:

Set dbs = OpenDatabase("C:\DATABASE\MYDB.MDB")

3.	Create a TableDef object for the external table:

Set tdf = dbs.CreateTableDef("Customer Detail")

 	4.	Set the TableDef object properties to refer to the attached table:

tdf.Connect = "ODBC;DSN=SSRVR1;UID=Fred;PWD=RHS;DATABASE=SQLDB;"

tdf.SourceTableName = "CustDetail"

5.	Append the TableDef object to the TableDefs collection with the Append method.  This step actually creates the object in the database file.

Note   Although this method is the most efficient way to access data stored in other Microsoft Jet databases, ODBC-based databases, and ISAM databases, it does not support SQL PassThrough queries.  If your application must support SQL PassThrough, please refer to Using SQL PassThrough.

Each of the data sources available through Data Access Objects (DAO) sometimes have specific considerations for using data.  The following topics can provide additional detailed information on using these data sources.

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

If your application expects particular behavior from the external database driver, you may want to review the registry or .INI file settings for the driver to make sure they meet your application's needs.  The following topics can provide additional detailed information on initializing each driver.

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Paradox Database Settings

Changing Text Data Source Settings

Changing Microsoft ODBC Settings


See Also

Customizing Windows Registry Settings for Data Access Objects

Data Access Overview

OpenDatabase Method

TableDef Object, TableDefs Collection

Using SQL PassThrough


Customizing Windows Registry Settings for Data Access Objects

See Also

Unless your application can work correctly with the default functionality of the Microsoft Jet database engine, you must change the settings in the Windows registry to suit your needs.  The Windows Registry can also be used to tune the operation of the installable ISAM and ODBC driver.  If your application can't accept the default behavior of the drivers, which is loaded from the shadow settings, you must create an entry in the Windows registry for your Microsoft Jet client application and override the default settings to get the appropriate behavior from your application.

To register Jet database engine settings for your application, create a Jet portion in your application's registry tree to manage the settings for the Jet database engine.  Then, add any values you want to specify to the registry tree.  If you have supplied any values in the Engines subfolder, Microsoft Jet loads those settings when the application starts.  Any values not entered in your client application's registry tree are loaded from shadow settings.

For example, to register Jet database engine settings for an application named "SOCCER.EXE" you would create a client registry tree similar to the following:

HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines

In the registry tree, you could override the default settings for the Jet database engine ISAM by setting the PageTimeout to a lower value (the default value is 5, or 500 milliseconds).  By setting PageTimeout to 1, your application will invalidate data in the internal cache in 100 milliseconds.  To register this new setting for your application, set the HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines\
PageTimeout value to 1.  When you start the application, the Jet database engine instance associated with SOCCER.EXE is configured with all settings in HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines.  Any settings not indicated in your client's registry tree will be loaded from the Jet database engine shadow settings for the client machine.  For example, if the client application registry folder HKEY_LOCAL_MACHINE\SOFTWARE\MyApps\Soccer\Jet\3.0\Engines\Jet contains only one entry that sets the value of PageTimeout to 1, only that setting will be changed from the default values found in HKEY_LOCAL_MACHINE\SOFTWARE\
Microsoft\Jet\3.0 during application initialization.

You can also edit the Windows Registry to specify:

Settings used for interaction with Microsoft FoxPro, Paradox, and dBASE databases.

Settings used by Microsoft ODBC for interaction with SQL databases.

Settings that affect how the Jet database engine reads and saves data.

Caution   Be very careful when changing registry settings so you do not change your system configuration in unintentional ways.


See Also

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Data Access Objects Overview

See Also

Data Access Objects (DAO) enable you to use a programming language to access and manipulate data in databases, and to manage databases, their objects, and their structure.

Microsoft Jet Database Engine

You can use Data Access Objects to manipulate databases in either the native Jet database engine .MDB format or in other installable ISAM database formats, including Fox, dBASE, Excel, Btrieve, Paradox, and delimited Text.  In addition, you can use the Microsoft Jet database engine to access Microsoft SQL Server and any other database that can be accessed with an ODBC driver using the same DAO code.

Data Access Objects

You can declare new data access object variables for any of the object types using the Dim and Set statements.  For example, the following code creates object variables for a Database object, a dynaset-type Recordset object, and a Field object:

Dim dbs As Database, rst As Recordset, fld As Field

Set dbs = OpenDatabase("BIBLIO.MDB")

Set rst = dbs.OpenRecordset("Authors", dbOpenDynaset)

Set fld = rst.Fields("Au_ID")

Data access objects have a default collection or property.  For example, the default collection of a Recordset object is the Fields collection and the default property of a Field object is the Value property.  You can simplify your code by taking advantage of these defaults.  For example, the following code sets the value of the PubID field in the current record:

Set rst = dbs.OpenRecordset("Publishers", dbOpenDynaset)

rst!PubID=99

You can use object variables and other DDL features to modify your database structure.  For example, you can add a new Field object to an existing table with the following code:

Dim dbs As Database, tdf as TableDef, fld As Field

Set dbs = OpenDatabase("BIBLIO.MDB")	' Open database.

Set tdf = dbs.TableDefs("Authors")

Set fld = tdf.CreateField("Address", dbText, 20)

tdf.Fields.Append fld	' Append to TableDef fields.

This code creates a new object variable for a Field object and adds it to a TableDef object with the Append method.  Because a TableDef object contains the definition of a table, the table now has a field named Address for entering data.  In much the same way, you can create new tables and new indexes.

DBEngine and Workspace Objects

All data access objects are derived from the DBEngine object, which represents the Jet database engine.  When your application starts, the Jet engine creates a default DBEngine.Workspace object that can be referenced through the Workspaces collection (Workspaces(0)).  You can open additional Workspace objects as needed.  Each Workspace object has a user ID and password associated with it.

Note   Unless you need to manipulate databases that have security enabled or create a separate transaction scope, you don't need to reference the DBEngine or Workspace objects.  The default DBEngine.Workspaces(0) object is assumed if it isn't specifically referenced.  For example, to open a database using DAO and create a table-type Recordset object, you can write the following code:

Dim dbs as Database, rst as Recordset

Set dbs = OpenDatabase("BIBLIO.MDB")

Set rst = dbs.OpenRecordset("Titles")

All Database objects opened against a Workspace object share a common transaction scope.  That is, when you use the BeginTrans method on a database, it applies to all other open databases opened in the Workspace object.  In the same way, using the CommitTrans method against one database applies to all other databases opened in the Workspace object.

Security

You can restrict access to one or more .MDB databases or their tables using security settings established and managed by the Jet database engine.  In your code, you can establish Group and User objects to define the scope and level of permissions available to individual users on an object-by-object basis.  For example, you can establish permissions for a specific user to provide read-only access to one table and full access to another.

Important   Before you can establish or alter any security settings, you need to gain access to the system database file associated with the .MDB database.  This file can only be created by a special utility included with Microsoft Access version 2.0 or higher.  Without this file, your application can't activate security for an .MDB database.


See Also

Activating Security

Data Access Overview

Database Object, Databases Collection

DBEngine Object

Workspace Object, Workspaces Collection


Locking Behavior in Multiuser Applications

See Also

Version 3.0 of the Microsoft Jet database engine contains a number of improvements to locking behavior, which include support for multithreading and implicit transactions.  This new behavior differs from the default behavior in Microsoft Jet version 2.x in some key areas that might affect existing Microsoft Jet applications.  This topic describes the similarities and differences in the two locking models and suggests coding strategies that enhance the performance of applications [image] new and existing [image] by taking advantage of the new model.

Using Explicit Transactions

Application code that uses explicit transactions won't be affected by changes in the locking strategy from Microsoft Jet version 2.x to Microsoft Jet version 3.0.  Explicit transactions are those that use a BeginTrans method followed by a conditional expression that determines the success of operations in the transaction.  If all operations in the transaction succeed, the application code calls the CommitTrans method to save the data to the database; if any operation fails, the application code cancels the effects of all operations by calling the Rollback method.

Implicit Transactions with SQL DML Commands

SQL Data Manipulation Language (DML) commands, such as UPDATE, INSERT, or DELETE, cause the Jet database engine to start an explicit transaction to process the commands.  Because these commands frequently involve several rows of data, they are often referred to as "bulk" or "set" operations.  This behavior is the same in both versions of the Jet database engine.

Multiuser Programming Considerations without Transactions

In an environment where multiple users are allowed concurrent access to data, Microsoft Jet version 2.x and Microsoft Jet version 3.0 behave differently in the areas of locking behavior, which specifies when locked records and pages are released, and latency, which determines when a user sees the results of other users' additions or changes.

Locking behavior in Microsoft Jet version 3.0 is improved by reducing the number of times data is read from and written to disk.  In version 2.x, data was written after each Recordset.Update method; in version 3.0, however, locks on the page containing individual records remain in place until the Microsoft Jet engine has accumulated enough data to fill the data cache or until two seconds (or the number of seconds specified in the Jet Engine SharedAsyncDelay registry key for your application) have elapsed since the start of the implicit transaction and the ImplictCommitSync registry setting is set to No.  These registry settings are described in Changing Microsoft Jet Engine ISAM Settings.

Concurrent access to data in a multiuser application is reduced compared with version 2.x code, as locks are usually held by an individual user for a longer period of time.  Although this locking strategy appears to reduce concurrency, it can increase performance in certain types of applications by reducing the number of read, write, and lock operations that would otherwise occur.  Any delays in existing application code can be minimized by adding explicit transaction code to emulate the Microsoft Jet 2.x locking behavior.  The following example illustrates this technique.

Example

This code example illustrates a typical scenario that relies on the Microsoft Jet 3.0 locking strategy.  To emulate Microsoft Jet 2.x locking behavior, add the Workspace.BeginTrans method before opening the record buffer for editing with the Recordset.Edit method, and add the Workspace.CommitTrans method after the Recordset.Update method to force Microsoft Jet to write the edits to disk.

Set rst = OpenRecordset("SELECT * FROM Customer", dbOpenDynaset)
While NOT rst.EOF
wrk.BeginTrans
rst.Edit
rst.CustId = CustId
rst.ClstNm = CLstNm
rst.Update
wrk.CommitTrans

rst.MoveNext
Wend

Latent Changes

Another change in Microsoft Jet version 3.0 involves the amount of time it takes for changes made by one user to appear to other users.  Because this behavior is also related to the delay in writing data to disk, the solution is the same.

To make sure data is written to disk at the time you expect, you can modify your code to use explicit transactions to emulate Microsoft Jet 2.x locking behavior, as in the previous example.  This solves the latency problem and ensures that no updates are pending after the transaction has been committed.  This also ensures that your changes will be visible to all users immediately after the transaction has completed.

Considerations for Handling Errors

In Microsoft Jet version 2.x, errors that occurred during update operations caused an immediate transfer to the error handler, which allowed the application to determine which record was being processed when the error occurred.  In Microsoft Jet version 3.0, critical errors that occur due to the inability to write data to disk are handled at the time Microsoft Jet tries to commit the data or write the contents of the cache to disk.  Because it is possible in a multithreaded environment for one thread to attempt to write data to disk while another thread continues to edit records, you must be aware of the possibilities for delayed error reporting and prepare your application's error handling routines accordingly.  If you need to emulate the error handling behavior in Microsoft Jet 2.x, just use the technique described previously for committing updates.

Note   Errors resulting from implicit updates (caused by writes from the filled cache) or explicit transaction commit (CommitTrans) operations are handled in the same way.


See Also

Changing Microsoft Jet Engine ISAM Settings


Obsolete Features in DAO

See Also

The following is a list of Data Access Object methods, properties, objects, and functions that have been replaced by more powerful, flexible, and easy-to-use features with Jet 3.0.  Each obsolete feature in the list has a corresponding replacement feature.

Obsolete feature	Replacement feature
All CreateDynaset methods	OpenRecordset method
All CreateSnapshot methods	OpenRecordset method
All ListFields methods	Fields collection
All ListIndexes methods	Indexes collection
CompactDatabase statement	DBEngine.CompactDatabase method
CreateDatabase statement	DBEngine.CreateDatabase method
DBEngine.FreeLocks method	DBEngine.Idle property
DBEngine.SetDefaultWorkspace method	DBEngine.DefaultUser and DBEngine.Password properties
DBEngine.SetDataAccessOption method	DBEngine.IniPath property
Database.BeginTrans method	WS.BeginTrans method
Database.CommitTrans method	WS.CommitTrans method
Database.Rollback method	WS.Rollback method
Database.DeleteQuerydef method	Delete method
Database.ExecuteSQL method	Execute method
Database.ListTables method	TableDefs collection
Database.OpenQuerydef method	QueryDefs collection
Database.OpenTable method	OpenRecordset method
OpenDatabase statement	DBEngine.OpenDatabase method
Querydef.ListParameters method	Parameters collection
Recordset.Indexes collection	TableDefs collection
Snapshot object	Recordset object
Dynaset object	Recordset object
Table object	Recordset object


See Also

Using Microsoft Jet Version 3.0 and 2.5


Selecting a Recordset Type for Data Access Objects

See Also

This topic discusses the types of Recordset objects available and how each type affects the performance and operation of your application.

Tables, Dynasets, and Snapshots

The Microsoft Jet database engine provides three kinds of recordsets: tables, which are actual database tables; dynasets, which can be updated; and snapshots, which cannot.

Table-type recordsets are available for any Microsoft Jet or installable ISAM database.  You cannot create a table-type recordset from an ODBC database.  When you use this type of Recordset object, it is as if you are directly opening the table.

A dynaset-type recordset provides an updatable set of records by fetching the key values that uniquely identify each of the rows.  The data from the bookmarked rows is fetched only when needed to populate the Table or Query datasheet view.  Using key values speeds the retrieval operation and minimizes network traffic, especially when browsing large tables.  Memo and OLE objects are not retrieved unless they need to be displayed.

Use a dynaset-type recordset when you are dealing with a large number of records (more than 500) or when the recordset you're using contains Memo or OLE Object fields.

A snapshot-type recordset cannot be updated.  The data contained in each of the rows is fetched when you create the recordset.  Creating a snapshot-type recordset can be much faster with small tables that do not contain a large number of columns and do not include Memo fields and OLE objects.  (Although this is a performance concern, Jet table snapshots containing Memo or OLE fields will not retrieve the data into the snapshot until it is actually referenced.)  You can also improve the retrieval speed of snapshot-type recordsets by making sure you are returning only the columns you need.

Use a snapshot-type recordset when you don't need to update the data in the source table, when you are dealing with a small number of records (fewer than 500), or when the Recordset object you're using doesn't contain Memo or OLE Object fields.

Using Forward-Only Snapshot Recordsets

By default, snapshot-type Recordset objects provide bidirectional scrolling capability.  If you do not need this capability (for example, if you only need to make a single pass through the records), you can use the dbForwardOnly flag to specify a forward-only recordset.  This allows the result set is to be copied to a nonscrollable buffer area.


See Also

Dynaset-Type Recordset

Snapshot-Type Recordset

Table-type Recordset


Converting a Database into a Replicable Form

See Also

You can convert your database by setting the Replicable property of your database to True.  For example, to make your database replicable, use the following code.

Sub MakeDBReplicable(strTargetDB)

Dim dbs As Database

' Open database in exclusive mode.

Set dbs = DBEngine(0).OpenDatabase(strTargetDB, True)

' Create property called "Replicable" and set to True.

dbs.Properties.Append dbs.CreateProperty("Replicable", dbText, _

True)	' Makes the DB replicable.

dbs.Close

End Sub

During the conversion process, the Microsoft Jet database engine maintains all the property settings of your original database.

Note   There is no method to make your database nonreplicable once it is made replicable.  Setting the Replicable property to False has no effect.


See Also

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local With

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts

Synchronizing Replicas


Keeping Objects Local Prior to Converting a Database into a Replicable Form

See Also

When a nonreplicable database is converted to a replicable form, all the objects in the database are converted to replicable objects unless you indicate otherwise.  Prior to converting your database, you can create and set the KeepLocal property on the object you do not want made replicable.  For example, if your database had a table containing confidential personnel information, such as salaries, you can set that table's KeepLocal property to True to keep it local while all other objects are made replicable when the database is made replicable.

Warning   The object on which you are setting the KeepLocal property might have already inherited that property from another object.  However, the value set by the other object has no affect on the behavior of the object you want to keep local.  You must directly set the property for each object.

If you set the KeepLocal property and the property has not already been appended or inherited, you will receive an error.  In the following example, the program sets the KeepLocal property to True and includes an error handler in case it receives the Property does not exist error.  If called, the error handler both appends and sets the property.

Sub SetKeepLocalEvenIfInherited(objParent As Object)

Const errPropNotFound = 3270

On Error GoTo KeepLocalPropHndlr

objParent.Properties("KeepLocal").Value = True

Exit Sub

KeepLocalPropHndlr:

If (Err = errPropNotFound) Then

objParent.Properties.Append qd.CreateProperty _

("KeepLocal", dbText, True)

Else

GoSub UserDefinedErrorHandler

End If

Resume Next

End Sub

The KeepLocal property cannot be applied to objects after they have been converted into a replicable form.  To make a replicable object local, set the object's Replicable property to False.

If you have set a relationship between two tables in your database, the KeepLocal property must be set the same for both tables.  Both tables must be local or both must be replicable.  If the property is not set the same at both tables, the conversion will fail.

Note   The KeepLocal and Replicable properties can be used only if your application has Microsoft Access with Briefcase Replication installed.


See Also

Converting a Database Into a Replicable Form

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts

Synchronizing Replicas


Making a Replica the Design-Master for the Replica Set

See Also

The design-master replica is the most important replica in a set because it is the only replica with which you can make changes to the structure of the database.  Under extreme circumstances [image] for example, if the original design-master replica becomes damaged or corrupted [image] you can use the ReplicaID property to set the DesignMasterID at the current replica and make that replica the new design-master for the set.  However, setting the DesignMasterID to the ReplicaID property setting for the current replica [image] when there is already another design-master replica [image] might partition your replica set into two irreconcilable sets and prevent any further synchronization of data.

Warning   Never create a second, concurrent design-master in a replica set.  The existence of a second design-master can result in the loss of data.

If you still need to make your replica the design-master, synchronize all the replicas in the replica set before changing the DesignMasterID at your replica.

You must have the replica open to make it the design-master.  The design-master replica is, by definition, a read/write replica.  If you make a replica that is designated read-only, it automatically becomes read/write.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making Additional Replicas

Making Objects Replicable or Local

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts

Synchronizing Replicas


Making Additional Replicas

See Also

When you convert your database by setting the Replicable property, you have just one replica (the design-master) in the replica set, and you must make your second replica from the first.  You can make your second and all subsequent replicas by using the MakeReplica method.  For example, you might use the following code to make a replica of your database.

Sub MakeAdditionalReplica(strReplicableDB, strNewReplica)

Dim dbs As Database

set dbs = DBEngine(0).OpenDatabase(strReplicableDB)

dbs.MakeReplica strNewReplica, "First Replica of" & strReplicableDB, _

dbRepMakeReadOnly

dbs.Close

End Sub

If you include the dbRepMakeReadOnly constant, then the replicable elements of the newly created replica cannot be modified.  Otherwise, users are able to make changes to the data in the new replica.  As the Microsoft Jet database engine creates the new replica, all property settings of the source replica are included in the new replica.  You can make subsequent replicas from either the design-master replica or from another replica in the set.

Note   Making a new replica copies all of the replicable objects and properties from the source replica to the new replica.  All attached tables are copied, but the path to an attached table may no longer be accurate because of the new replica's location on the network.  Be sure to test the new replica to determine if a new path needs to be established for any of the attached tables.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Objects Replicable or Local

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts

Synchronizing Replicas


Making Objects Replicable or Local

See Also

When a nonreplicable database is converted to a replicable form, all the objects in the database are converted to replicable objects unless their KeepLocal property was set to True.  After a database is made replicable, however, all new objects created at the design-master replica or any other replica in the set are treated as "local" objects.  Local objects remain at the replica where they were created and are not propagated around the replica set.  Each time you make a new replica in the set, all the replicable objects at the source replica are included in that new replica, but none of the local objects are included.

There may be instances when you create a new object at a replica and want to change it from local to replicable so that all end users can have it.  To change an object from local to replicable, you must either create the object at, or import it into, the design-master replica.  After the object is part of the design-master replica, you must set the object's Replicable property to True.

Warning   The object on which you are setting the Replicable property might have already inherited that property from another object.  However, the value set by the other object has no effect on the behavior of the object you want to make replicable.  You must directly set the property for each object.

If you set the Replicable property and the property has not already been appended or inherited, you will receive an error.  In the following example, the program sets the Replicable property to True and includes an error handler in case it receives the Property does not exist error.  If called, the error handler both appends and sets the property.

Sub SetReplicableEvenIfInherited(objParent As Object)

Const errPropNotFound = 3270

On Error GoTo ReplicablePropHndlr

objParent.Properties("Replicable").Value = True

Exit Sub

ReplicablePropHndlr:

If (Err = errPropNotFound) Then

objParent.Properties.Append qd.CreateProperty _

("Replicable", dbText, True)

Else

GoSub UserDefinedErrorHandler

End If

Resume Next

End Sub

At the next synchronization, the newly replicable object appears at the other replicas in the set.  Similarly, if you want to make a replicable object local, you set its Replicable property to False.  At the next synchronization, the object that was global is deleted at all replicas except the design-master replica.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts

Synchronizing Replicas


Moving Design-Master Status to Another Replica

See Also

The design-master replica is the most important replica in a set because it is the only replica with which you can make changes to the structure of the database.  Under certain circumstances, you might need to move the design-master status from one replica to another.  For example, you might have the design-master replica on your computer while another member of your development team has a replica on his or her computer.  While you are on vacation, you may want the other developer to be able to make design changes to the database.  As the following code example illustrates, you can use the ReplicaID property to establish a new DesignMasterID and synchronize the replicas.

' Open the current design-master in exclusive mode.

Set dbs = DBEngine(0).OpenDatabase(strOldDM, True)

' Open the new design-master.

set newdmdb = DBEngine(0).OpenDatabase(strNewDB)

dbs.DesignmasterID = newdmdb.ReplicaID

dbs.Synchronize strNewDB,dbRepImpExpChanges

dbs.Close

newdmdb.Close

You must have the design-master replica open to move the design-master status to another replica, and you must synchronize after moving the design-master status for it to take effect.

The design-master replica is a read/write replica.  If you move the design-master status to a replica that is designated read-only, the receiving replica is made read/write and the old design-master replica is made read-only.

If the replica serving as the design-master is erased or corrupted, you can designate another replica as the design-master; but there must be only one design-master at a time.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

Resolving Synchronization Conflicts

Synchronizing Replicas


Resolving Synchronization Conflicts

See Also

After synchronizing two replicas, you should review the database for conflicts.  You can determine if a conflict has occurred for a specific table by using the ConflictTable property on the table.  This property returns the name of the conflict table that contains the database records that conflicted during synchronization.  For example, to find the name of the conflict table associated with a table in your database, to examine each record conflict, and to take action to resolve the conflict, you might use the following code.

Sub Resolve (dbs As Database)

Dim tdf As TableDef, recErr As Recordset

For Each tdf In dbs.TableDefs

If (tdf.ConflictTable <> "") Then

Set recErr = dbs.OpenRecordset(tdf.ConflictTable)

' Process each record.

recErr.MoveFirst

While Not recErr.EOF

.	' Do conflict resolution.

.

.

recErr.Delete	' Remove conflicting record when finished.

recErr.MoveNext

Wend

recErr.Close

End If

Next tdf

End Sub

If there is no conflict table or the database is non-replicable, the property returns a zero-length string.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

Moving Design-Master Status to Another Replica

Synchronizing Replicas


Synchronizing Replicas

See Also

You can keep the replicas synchronized using the Synchronize method.  By specifying the target database filename in dbspathname, you can synchronize one user's replica with another replica in the set.  Various types of exchanges can be performed as specified by the intexchgtype argument.  If no argument is provided, the exchange is bidirectional (import and export).  For example, you might use the following code to do a two-way synchronization between replicas.

Sub SynchronizeDBs(strDBName, strSyncTargetDB)

Dim dbs As Database

set dbs = DBEngine(0).OpenDatabase(strDBName)

'Synchronize replicas (bidirectional exchange).

dbs.Synchronize strSyncTargetDB, dbRepImpExpChanges

dbs.Close

End Sub

When the Microsoft Jet database engine synchronizes replicas, it always synchronizes design changes first.  Both replicas must be at the same design level before data can be exchanged.  For example, an exchange of type dbRepExportChanges might cause design changes to be made at the current replica even though data changes flow only from the current replica to the designated target.  If both replicas have the same ReplicaID property setting because of being copied or both have design-master status, the synchronization fails.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts


Accessing Data in a Btrieve Database

See Also

You can either attach Btrieve tables to your Microsoft Jet database (version 2.5 or earlier only) or open them directly.  The procedures for accessing the data in Btrieve files (versions 5.1x and 6.0) are similar to the procedures used to access data in other external data sources.  Special considerations for using Btrieve data are provided in the following sections.

Attaching a Btrieve Table

To attach a Btrieve table in your Jet database, use the OpenDatabase method to open the database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Btrieve table you want to attach.

When specifying connection information for Btrieve data, use the following specifications.

For	Use
Source database type	Btrieve
Database name	The full path to the File.DDF data definition file
Source table name	The name of the table (as identified in File.DDF)
Example

The following example shows how to attach an external Btrieve table and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfAttachedTable As TableDef

' Open Jet database named TEST.MDB.

Set dbsJet = OpenDatabase("C:\ACCESS\DATA\TEST.MDB")

' Create TableDef object.

Set tdfAttachedTable = dbsCurrent.CreateTableDef("Attached Btrieve Table")

' Set connection information.

tdfAttachedTable.Connect = "Btrieve;DATABASE=N:\FILE.DDF"

tdfAttachedTable.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfAttachedTable

' Display confirmation message.

MsgBox "Finished attaching " & tdfAttachedTable.SourceTableName & ".", 0

Opening a Btrieve Table

To open a Btrieve table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

Example

The following example shows how to open an external Btrieve table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external Btrieve data definition file.

Set dbsJet = OpenDatabase("N:\FILE.DDF", FALSE, FALSE, "BTRIEVE;")

' Create Recordset object from Accounts table.

Set rstAccounts = dbsCurrent.OpenRecordset("Accounts")

Data Definition File (.DDF) Requirements

To use Btrieve tables, you must have the data definition files FILE.DDF and FIELD.DDF.  These files describe the structure of your tables.  These files are created by Xtrieve or by another .DDF file-building program.  After you've attached a Btrieve table, if you delete or move these files or your Btrieve data files, you won't be able to open an external Btrieve table.

Data Type Conversions

When you read data from a Btrieve file, Microsoft Jet translates each Btrieve data type into the corresponding Microsoft Jet data type, as shown in the following table.

Btrieve data type	Microsoft Jet data type
String, lstring, zstring	String
Integer (1-, 2-, or 4-byte), autoinc (2- or 4-byte)	Long
Float or bfloat (4-byte)	Single
Float or bfloat (8-byte), decimal, numeric	Double
Money	Currency
Logical, bit	Boolean
Date, time	Date/Time
Note	Memo
Lvar	Memo
Note   Any Btrieve field that exceeds 255 bytes is treated as a Memo field.

Additional Information

For additional information and a current listing of Options settings, consult your Btrieve documentation.


See Also

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Accessing Data in a dBASE Database

See Also

You can either attach dBASE tables (.DBF files) to your Microsoft Jet database or open them directly.  The procedures for accessing the data in dBASE tables (versions III, IV, or 5.x) are similar to the procedures used to access data in other external data sources.  Special considerations for using dBASE data are provided in the following sections.

Attaching a dBASE Table

To attach a dBASE table in your Jet database, use the OpenDatabase method to open the Microsoft Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the dBASE table you want to attach.

When specifying connection information for dBASE data, use the following specifications.

For	Use
Source database type	One of the following: dBASE III dBASE IV dBASE 5.0
Database name	The full path to the directory containing the dBASE files you intend to access
Source table name	The name of the table (the .DBF filename without the extension or the complete filename with the extension but substituting a number sign (#) for the dot (.) that precedes the filename extension)
The following example shows how to attach an external dBASE IV table and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfAttachedTable As TableDef

' Open Jet database named TEST.MDB.

Set dbsJet = OpenDatabase("C:\ACCESS\DATA\TEST.MDB")

' Create TableDef object.

Set tdfAttachedTable = dbsCurrent.CreateTableDef("Attached dBASE Table")

' Set connection information.

tdfAttachedTable.Connect = "dBASE IV;DATABASE=\\dBASE\Data\AP"

tdfAttachedTable.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfAttachedTable

' Display confirmation message.

MsgBox "Finished attaching " & tdfAttachedTable.SourceTableName & ".", 0

Opening a dBASE Table

To open a dBASE table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

The following example shows how to open an external dBASE III table directly and create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external dBASE database.

Set dbsJet = OpenDatabase _

("\\dBASE\Data\AP", False, False, "dBASE III;")

' Create Recordset object from Accounts table.

Set rstAccounts = dbsCurrent.OpenRecordset("Accounts")

Data Type Conversions

When you read data from a dBASE file, Microsoft Jet engine translates each dBASE data type into the corresponding Jet data type, as shown in the following table.

dBASE data type	Microsoft Jet data type
Character	String
Numeric, Float	Double
Logical	Boolean
Date	Date/Time
Memo	Memo
OLE	OLE
Deleted Records

In most cases, if you delete a record when working with external data, the record is actually removed from the source table.  When working with dBASE tables, however, deleted records aren't actually removed until the table is packed using dBASE commands or utilities.  The Jet engine's CompactDatabase method of the DBEngine object works only on Jet databases; it has no effect on dBASE databases.

You can tell the Jet engine not to include deleted records by setting the Deleted parameter of the initialization settings to True.  If you set the Deleted parameter to False, all records are included in any Recordset objects you create, including deleted records.

Indexes

When you attach or open a dBASE table, you can tell the Jet engine to use one or more dBASE index (.NDX or .MDX) files to improve performance.  The Jet engine keeps track of the indexes in a special information (.INF) file.  When you use Visual Basic to attach or open a dBASE table, you must create the .INF file using a text editor or use the one created by Microsoft Access.  The name of the .INF file must correspond to the name of the external table.  In order for the Jet engine to easily locate associated indexes, it's best to put the .INF file in the same directory as the associated table.  However, if the table is on a read-only share, you can specify a different path using the INFPath entry in the initialization settings.

Each entry in the .INF file contains an index number (using the identifiers NDXn for dBASE III or NDXn or MDXn for dBASE IV) and an index filename (for example, LASTNAME.NDX).  The entries are preceded by a source database type.  As an example, the .INF file for a dBASE III table named Authors would be named AUTHORS.INF, and could contain the following entries.

[dBASE III]

NDX1=AuthorID.NDX

NDX2=LastName.NDX

NDX3=Zip.NDX

To specify a unique index, add the tag or filename for the unique index to the .INF file using the identifier UIDXn.  Add the entry under the database type heading, as shown in the following example.

[dBASE III]

NDX1=AuthorID.NDX

NDX2=LastName.NDX

NDX3=Zip.NDX

UIDX1=AauthorID.NDX

When you use the Jet engine to update the data in your .DBF file, the Jet engine also updates the index files to reflect your changes.  If you attach or open a .DBF file and associate an index (.NDX, or .MDX) file, the Jet engine needs to be able to find the index file to open the attached table.  If you delete or move index files or the .INF file, the Jet engine can't use the index and doesn't keep the index up-to-date.  If index files aren't current, keep in mind that your query results will be unpredictable.

Memo Fields

dBASE Memo fields are located in files separate from their associated tables.  When attaching or opening dBASE tables with associated Memo fields, the Memo files must be located in the same directory as the .DBF files.

Additional Information

For additional information, consult your dBASE documentation.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Accessing Data in a Lotus Spreadsheet

See Also

You can either attach Lotus spreadsheets to your Microsoft Jet database or open them directly.  The procedures for accessing the data in Lotus files (versions WKS, WK1, or WK3) are similar to the procedures used to access data in other external data sources.  Special considerations for using Lotus data are provided in the following sections.

How to Reference Tables, Fields and Records

You can reference an entire Lotus spreadsheet, a named range of cells within a spreadsheet, or an arbitrary (unnamed) range of cells.  The conventions for referring to sheets and arbitrary ranges differ depending on whether you are accessing single-sheet (WKS and WK1) or multisheet (WK3 and WK4) files.

To reference an entire WLS or WK1 spreadsheet, enter the path and filename.  Use the number sign (#) to separate the filename and extension (for example, C:\LOTUS\SALES#WK3).  To reference an entire sheet in a WK3 or WK4 file, specify the sheet name followed by a colon (for example, SHEET1:).

To reference an arbitrary range of cells in a WKS or WK1 spreadsheet, specify the starting and ending cells of the range separated by two periods (for example, A1..E15).  To reference an arbitrary range of cells in a WK3 or WK4 file, specify the sheet name followed by a colon and the starting and ending cells of the range separated by two periods (for example, SHEET1:A1..E15)

To reference a named range of cells in any Lotus spreadsheet, you must name the range before attempting to open or attach it.  You can name a range of cells by highlighting the range, choosing Range Name Create from the menu, and entering the name of the range (for example, ThirdQtrSales).  The name you enter becomes the name of the data table attached or opened using the Lotus ISAM.  You can't directly reference individual fields and records in a Lotus data table.

Attaching a Lotus Spreadsheet

To attach a Lotus spreadsheet in your Jet database, use the OpenDatabase method to open the Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Lotus file you want to attach.  You can specify either the named range within a spreadsheet or the entire spreadsheet.

When specifying connection information for Lotus data, use the following specifications.

For	Use
Source database type	Lotus WKS*, Lotus WK1**, Lotus WK3**, or Lotus WK4**.
Database name	The full path to the Lotus spreadsheet.
Source table name	The name of the spreadsheet or a range specified in the spreadsheet.
*	Lotus WKS worksheets are opened as read-only data sources; you cannot add, edit, or delete rows.
**	Lotus WK1, WK3, and WK4 worksheets are opened as write-once, read-many data sources; you can add new rows, but you cannot edit or delete existing rows.
The following example shows how to attach an external Lotus spreadsheet and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfThirdQtr As TableDef

' Open Jet database named NORTHWIND.MDB.

Set dbsJet = OpenDatabase("C:\DB\DATA\NORTHWIND.MDB")

' Create TableDef object.

Set tdfThirdQtr = dbsCurrent.CreateTableDef("Attached Lotus Table")

' Attach Lotus range Third Quarter in spreadsheet

' C:\LOTUS\EXAMPLES\SALES.WK3.

tdfThirdQtr.Connect = "LOTUS WK3; _
Database=C:\LOTUS\EXAMPLES\SALES.WK3"

tdfThirdQtr.SourceTableName = "THIRDQTR"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfThirdQtr

' Display confirmation message.

MsgBox "Finished attaching " & tdfThirdQtr.SourceTableName & ".", 0

Opening a Lotus Spreadsheet

To open a Lotus spreadsheet directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

The following example shows how to open an external Lotus spreadsheet and then create a Recordset object from the named range THIRDQTR.

Dim dbsJet As Database

Dim rstThirdQtr As Recordset

' Open external Lotus spreadsheet table.

Set dbsJet = OpenDatabase _

("C:\LOTUS\EXAMPLES\SALES.WK3", False, False, "LOTUS WK3;")

' Create Recordset object from Sales worksheet range "THIRDQTR".

Set rstThirdQtr = dbsCurrent.OpenRecordset("THIRDQTR")

Benefits and Problems with Using Lotus Spreadsheet

Directly attaching or opening the Lotus spreadsheets allows other Lotus users to continue accessing the files from their own applications.

Additional Information

For additional information, consult your Lotus documentation.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Accessing Data in a Microsoft Excel Worksheet or Workbook

See Also

You can either attach Microsoft Excel worksheets and workbooks to your Microsoft Jet database or open them directly.  The procedures for accessing the data in Microsoft Excel files (versions 3.0, 4.0, 5.0, or 7.0) are similar to the procedures used to access data in other external data sources.  Special considerations for using Microsoft Excel data are provided in the following sections.

How to Reference Tables, Fields and Records

You can reference either a Microsoft Excel worksheet, a worksheet within a workbook, a named range of cells within a worksheet, or an arbitrary (unnamed) range of cells in a worksheet (for example, A1:E15).  The conventions for referring to worksheets and arbitrary ranges differ depending on whether you are accessing single-sheet (Microsoft Excel 3.0 and Microsoft Excel 4.0) or workbook (Microsoft Excel 5.0 and Microsoft Excel 7.0) files.

To reference an entire Microsoft Excel 3.0 or Microsoft Excel 4.0 worksheet, enter the path and filename.  Use the number sign (#) to separate the filename and extension (for example, C:\EXCEL\SALES#XLS).  To reference an entire sheet in an Microsoft Excel 5.0 and Microsoft Excel 7.0 workbook, specify the sheet name followed by a dollar sign (for example, SHEET1$).

To reference an arbitrary range of cells in an Microsoft Excel 3.0 or Microsoft Excel 4.0 worksheet, specify the starting and ending cells of the range separated by a colon (for example, A1:E15).  To reference an arbitrary range of cells in a worksheet in an Microsoft Excel 5.0 and Microsoft Excel 7.0 workbook, specify the sheet name followed by a dollar sign and the starting and ending cells of the range separated by a colon (for example, SHEET1$A1:E15)

To reference a named range of cells in any Microsoft Excel worksheet, you must name the range before attempting to open or attach it.  You can name a range of cells by highlighting the range, clicking Insert Name Define on the Insert menu, and entering the name of the range (for example, ThirdQtrSales).  The name you enter becomes the name of the data table attached or opened using the Microsoft Excel ISAM.  You can't directly reference individual fields and records in an Microsoft Excel data table.

Attaching a Microsoft Excel Worksheet

To attach a Microsoft Excel worksheet or workbook in your Jet database, use the OpenDatabase method to open the Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Microsoft Excel file you want to attach.  You can specify either the named range within a worksheet, the entire worksheet, or the entire workbook.

When specifying connection information for Microsoft Excel data, use the following specifications.

For	Use
Source database type	Microsoft Excel 3.0, Microsoft Excel 4.0, Microsoft Excel 5.0, or Microsoft Excel 7.0.
Database name	The full path to the Microsoft Excel worksheet or workbook.
Source table name	The name of the worksheet or a range specified in the worksheet.  The Jet database engine does not recognize the exclamation point (!); it uses the dollar sign ($) instead.  For example, the worksheet name SHEET!NAME is shown as table SHEET$NAME.  If you use quotation marks in the sheet name in Microsoft Excel, you must also use them when you specify it as part of the table name.  For example, 'MY SHEET'$NAME.
The following example shows how to attach an external Microsoft Excel worksheet and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfThirdQtr As TableDef

' Open Jet database named NORTHWIND.MDB.

Set dbsJet = OpenDatabase("C:\DB\DATA\NORTHWIND.MDB")

' Create TableDef object.

Set tdfThirdQtr = dbsCurrent.CreateTableDef("Attached Microsoft _
Excel" & "Table")

' Attach Microsoft Excel table Third Quarter in worksheet C:\EXCEL\EXAMPLES\SALES.XLS.

tdfThirdQtr.Connect = "EXCEL 5.0; Database=C:\EXCEL\EXAMPLES\SALES.XLS"

tdfThirdQtr.SourceTableName = "THIRDQTR"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfThirdQtr

' Display confirmation message.

MsgBox "Finished attaching " & tdfThirdQtr.SourceTableName & ".", 0

Opening a Microsoft Excel Worksheet

To open a Microsoft Excel worksheet directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

The following example shows how to open an external Microsoft Excel worksheet and then create a Recordset object from the named range THIRDQTR.

Dim dbsJet As Database

Dim rstThirdQtr As Recordset

' Open external Microsoft Excel worksheet table.

Set dbsJet = OpenDatabase _

("C:\EXCEL\EXAMPLES\SALES.XLS", False, False, "EXCEL 5.0;")

' Create Recordset from Sales worksheet.

Set rstThirdQtr = dbsCurrent.OpenRecordset("THIRDQTR")

Special Caveats for Using Microsoft Excel Worksheets

You cannot delete rows from Microsoft Excel worksheets.  You can clear data from individual cells in the worksheet, but you cannot modify cells that contain formulas.  Also, you cannot create indexes.  Because the database engine does not support multiple users of a Microsoft Excel worksheet, worksheets are opened exclusively for a single user.  Data that has been encrypted in Microsoft Excel cannot be read by the Microsoft Excel driver.  If the database engine encounters encrypted data, you will not be able to access that data.

Benefits/problems with Using an Microsoft Excel Worksheet

Directly attaching or opening the Microsoft Excel worksheets and workbooks allows other Microsoft Excel users to continue accessing the files from their own applications.

Additional Information

For additional information, consult your Microsoft Excel documentation.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Accessing Data in a Microsoft FoxPro Database

See Also

You can either attach Microsoft FoxPro tables to your Microsoft Jet database or open them directly.  The procedures for accessing the data in FoxPro files (versions 2.0, 2.5, or 2.6) are similar to the procedures used to access data in other external data sources.  Special considerations for using FoxPro data are provided in the following sections.

Attaching a Microsoft FoxPro Table

To attach a Microsoft FoxPro table in your Jet database, use the OpenDatabase method to open the database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the FoxPro table you want to attach.

When specifying connection information for FoxPro data, use the following specifications.

For	Use
Source database type	One of the following: FoxPro 2.0 FoxPro 2.5 FoxPro 2.6
Database name	The full path to the directory containing the FoxPro files you intend to access.
Source table name	The name of the table (the .DBF filename without the extension or the complete filename with the extension but substituting a number sign (#) for the dot (.) that precedes the filename extension).
The following example shows how to attach an external FoxPro version 2.5 table and then display a message box as confirmation.  Note that this example uses a number sign (#) in the SourceTableName property to specify a nonstandard extension (.XYZ).

Dim dbsJet As Database

Dim tdfFoxTable As TableDef

' Open Jet database named TEST.MDB.

Set dbsJet = OpenDatabase("C:\ACCESS\DATA\TEST.MDB")

' Create TableDef object.

Set tdfFoxTable = dbsCurrent.CreateTableDef("Attached FoxPro Table")

' Set connection information.

tdfFoxTable.Connect = "FoxPro 2.6;DATABASE=\\FOXPRO\DATA\AP"

tdfFoxTable.SourceTableName = "ACCOUNTS#XYZ"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfFoxTable

' Display confirmation message.

MsgBox "Finished attaching " & tdfFoxTable.SourceTableName & ".", 0

Opening a Microsoft FoxPro Table

To open a Microsoft FoxPro table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

The following example shows how to open an external FoxPro version 2.0 table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external FoxPro database.

Set dbsJet = OpenDatabase _

("\\FOXPRO\DATA\AP", False, False, "FoxPro 2.0;")

' Create Recordset object from Accounts table.

Set rstAccounts = dbsCurrent.OpenRecordset("Accounts")

Data Type Conversions

When you read data from a FoxPro file, the Jet engine translates each FoxPro data type into the corresponding Jet data type, as shown in the following table.

FoxPro data type	Microsoft Jet data type
Character	String
Numeric, Float	Double
Logical	Boolean
Date	Date/Time
Memo	Memo
General	OLE Object
Deleted Records

In most cases, if you delete a record when working with external data, the record is actually removed from the source table.  When working with FoxPro tables, however, deleted records aren't actually removed until the table is packed using FoxPro commands or utilities.  The Jet engine's CompactDatabase method of the DBEngine object works only on Jet databases; it has no effect on Microsoft FoxPro databases.

You can tell the Jet database engine not to include deleted records by setting the Deleted parameter of the initialization settings to True.  If you set the Deleted parameter to False, all records are included in any Recordset objects you create, even deleted records.

Indexes

When you attach or open a FoxPro table, you can tell the Jet engine to use one or more FoxPro index (.IDX or .CDX) files to improve performance.  The Jet engine keeps track of the indexes in a special information (.INF) file.  When you use Visual Basic to attach or open a FoxPro table, you must create the .INF file using a text editor.  The name of the .INF file must correspond to the name of the external table.  In order for The Jet engine to easily locate associated indexes, it's best to put the .INF file in the same directory as the associated table.  However, if the table is on a read-only share, you can specify a different path using the INFPath entry in the Jet\3.0\Engines\Xbase folder in the Windows Registry (Jet. 3.0) or in your application's .INI file (Jet 2.5).  You can also use the index created by Microsoft Access if you use Microsoft Access to attach or open a FoxPro table.

Each entry in the .INF file contains an index number (using the identifiers CDXn or IDXn) and an index filename (for example, LastName.CDX).  The entries are preceded by a source database type.  As an example, the .INF file for a FoxPro 2.0 table named Authors would be named Authors.INF, and could contain the following entries.

[FoxPro 2.0]

CDX1=AuthorID.CDX

CDX2=LastName.CDX

CDX3=Zip.CDX

To specify a unique index, add the tag or filename for the unique index to the .INF file using the identifier UIDXn.  If the table will be opened only from version 2.0 of the Jet database engine, add the entry under the database type heading, as shown in the following example.

[FoxPro 2.0]

CDX1=AuthorID.CDX

CDX2=LastName.CDX

CDX3=Zip.CDX

UIDX1=AuthorID.CDX

When you use The Jet engine to update the data in your .DBF file, The Jet engine also updates the index files to reflect your changes.  If you attach or open a .DBF file and associate an index (.IDX or .CDX) file, The Jet engine needs to be able to find the index file to open the attached table.  If you delete or move index files or the .INF file, The Jet engine can't use the index and doesn't keep the index up-to-date.  If index files aren't current, keep in mind that your query results will be unpredictable.

Memo Fields

FoxPro Memo fields are located in files separate from their associated tables.  When attaching or opening FoxPro tables with associated Memo fields, the Memo files must be located in the same directory as the .DBF files.

Additional Information

For additional information, consult your Microsoft FoxPro documentation.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Accessing Data in a Microsoft Jet Database

See Also

You can either attach external Microsoft Jet database tables to your local Jet database or open them directly.  The procedures for accessing the data in external Jet database tables are similar to the procedures used to access data in other external data sources.

Attaching an External Microsoft Jet Table

To attach an external Jet database table in your local Jet database, use the OpenDatabase method to open the local Jet database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the external Jet database table you want to attach.

When specifying connection information for external Jet database tables, use the following specifications.

For	Use
Source database type	Not applicable.
Database name	The full path to the .MDB file.
Source table name	The name of the table.
The following example shows how to attach an external Jet database table and then display a message box as confirmation.  Notice that the connection string begins with just a semicolon (;) rather than a source database type.  A source database type isn't applicable when connecting to external databases that use the Jet database engine.

Dim dbsJet As Database

Dim tdfJetTable As TableDef

' Open Jet database named TEST.MDB.

Set dbsJet = OpenDatabase("C:\ACCESS\DATA\TEST.MDB")

' Create TableDef object.

Set tdfJetTable = dbsJet.CreateTableDef("Attached Jet Table")

' Set connection information.

tdfJetTable.Connect = ";DATABASE=\\ACCESS\DATA\AP.MDB"

tdfJetTable.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfJetTable

' Display confirmation message.

MsgBox "Finished attaching " & tdfJetTable.SourceTableName & ".", 0

Opening an External Microsoft Jet Table

To open an External Microsoft Jet table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

The following example shows how to open an external Jet database table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external Jet database named AP.

Set dbsJet = OpenDatabase _

("\\ACCESS\DATA\AP.MDB", False, False, "")

' Open a Recordset on Accounts table.

Set rstAccounts = dbsCurrent.OpenRecordset("Accounts")


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Accessing Data in a Paradox Database

See Also

You can either attach Paradox tables to your local Microsoft Jet database or open them directly.  The procedures for accessing the data in Paradox files (versions 3.x and 4.x) are similar to the procedures used to access data in other external data sources.  Special considerations for using Paradox data are provided in the following sections.

Attaching a Paradox Table

To attach a Paradox table in your Microsoft Jet database, use the OpenDatabase method to open the database, create a TableDef object, and set the Connect method and SourceTableName method of the TableDef object to indicate the path and name, respectively, of the Paradox table you want to attach.

When specifying connection information for Paradox tables, use the following specifications.

For	Use
Source database type	One of the following: Paradox 3.X Paradox 4.X Paradox 5.X
Database name	The full path to the directory containing the Paradox files you intend to access
Source table name	The name of the table (the .DB filename without the extension).
The following example shows how to attach an external Paradox version 3.x table and then display a message box as confirmation.

Dim dbsJet As Database

Dim tdfParadox As TableDef

' Open Jet database named TEST.MDB.

Set dbsJet = OpenDatabase("C:\ACCESS\DATA\TEST.MDB")

' Create TableDef object.

Set tdfParadox = dbsCurrent.CreateTableDef("Attached Paradox _

Table")

' Set connection information.

tdfParadox.Connect = "Paradox 3.X;DATABASE=\\PDOX\DATA\AP"

tdfParadox.SourceTableName = "Accounts"

' Append TableDef object to create link.

dbsCurrent.TableDefs.Append tdfParadox

' Display confirmation message.

MsgBox "Finished attaching " & tdfParadox.SourceTableName & ".", 0

Opening a Paradox Table

To open a Paradox table directly, create a Database object and use the OpenDatabase method to indicate the path, exclusive access value, read-only value, and data source name.

The following example shows how to open an external Paradox version 4.x table and then create a Recordset object from the table.

Dim dbsJet As Database

Dim rstAccounts As Recordset

' Open external Paradox database named AP.

Set dbsJet = OpenDatabase _

("\\PDOX\DATA\AP", False, False, "Paradox 4.X;")

' Create Recordset from Accounts table.

Set rstAccounts = dbsCurrent.OpenRecordset("Accounts")

Data Type Conversions

When you read data from a Paradox table, the Jet engine translates each Paradox data type into the corresponding Jet engine data type, as shown in the following table.

Paradox data type	Microsoft Jet data type
Alphanumeric	Text
Number	Double
Short number	Integer
Currency	Currency
Date	Date/Time
Memo	Memo
OLE	OLE Object (note that the Jet engine recognizes the object but won't let you open it)
Logical (Paradox 5.X)	Boolean
Integer (Paradox 5.X)	Long
Timestamp (Paradox 5.X)	Date/Time
Binary (Paradox 5.X)	Byte
BCD (Paradox 5.X)	Double
Time (Paradox 5.X)	Date/Time
Autoinc (Paradox 5.X)	Counter
Note   Paradox Graphic, Binary, and Formatted memo types aren't supported and will not appear when you display external Paradox tables.

Indexes and Keys

Paradox stores important information about a table's primary key in an index (.PX) file.  If you attach or open a Paradox table that has a primary key, the Jet engine needs to be able to find the .PX file to open the attached table.  After you've attached a Paradox table, if you delete or move the associated .PX file, you won't be able to open the external table.

If you attach or open a Paradox table that doesn't have a primary key, you can't update data in the table using Microsoft Jet, and you can't open the table in shared mode.  If you want to be able to update the table or open the table in shared mode, define a primary key for the table using Paradox commands.

Network Paths

When you attach or open a Paradox table that resides on a server and is shared by multiple users, you must set the ParadoxNetPath option in the JET\3.0\ENGINES\PARADOX folder of the Windows registry to the path for either the PARADOX.NET file (for Paradox 3.x) or the PDOXUSRS.NET file (for Paradox 4.x).  For example, if the PARADOX.Net file is on drive Q in the WRKGRP directory, set ParadoxNetPath as follows.

ParadoxNetPath=Q:\WRKGRP

Important   The ParadoxNetPath, including the drive letter, must be consistent for all users sharing a particular database (directory).  For example, if the PARADOX.NET file is in the WRKGRP directory on drive Q for one user of the database, it must be in the WRKGRP directory on drive Q for all other users of the database.

Additional Information

For additional information, consult your Paradox documentation.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing Btrieve Database Settings

See Also

The Microsoft Jet database engine currently supports Btrieve only in the 16-bit version.  No 32-bit Btrieve driver is currently available, so the information in this topic refers only to 16-bit application development.

Initialization (.INI) File Settings

When accessing Btrieve files, the Btrieve driver uses the [BTRIEVE] section of either the WIN.INI file (for Btrieve version 5.1x) or the NOVDB.INI file (for Btrieve version 6.0).  If you specify that you want to access Btrieve files, the Visual Basic Setup program adds the following entry to the appropriate initialization file:

[BTRIEVE]

Options=/m:64 /p:4096 /b:16 /f:20 /l:40 /n:12 /t:C:\DB\BTRIEVE.TRN

The following table describes each of these Options switches.

Switch	Definition
/m	Memory size
/p	Page size
/b	Pre-image buffer size
/f	Open files
/l	Multiple locks
/n	Files in a transaction
/t	Transaction file name
Important   If you expect to share a Btrieve database, make sure that the path given for the transaction file (as specified by the /t switch above) is available on the network to all users of the database.  Generally, this file is placed on a common server that all users can access.  The default setting for the Options entry doesn't take this into account.

In addition, if you run out of resources while working with Btrieve data, add the switch /u:2 to the Options entry, and then restart Visual Basic.

Also, keep in mind that if you install another application that modifies the Options settings in the initialization file from the values shown previously, Visual Basic may not work correctly with your Btrieve files.

Note   For additional information and a current listing of Options settings, consult your Btrieve documentation.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing dBASE Database Settings

See Also

When you install the dBASE database driver, the Setup program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys for Jet 3.0.  For Jet 2.5, the initialization settings are in the VB.INI (or <APPNAME>.INI file).  The following sections describe initialization and ISAM Format settings for both the 16-bit (Jet 2.5) and 32-bit (Jet 3.0) dBASE database drivers.

dBASE Initialization Settings (Jet 3.0)

The JET\3.0\ENGINES\XBASE folder includes initialization settings for the MSXB3032.DLL driver, used for access to external dBASE data sources.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSXB3032.DLL

NetworkAccess=On

PageTimeout=600

INFPath=C:\DBASE\SYSTEM

CollatingSequence=ASCII

DataCodePage=OEM

Deleted=Off

Century=Off

Date=American

Mark=47

Exact=Off

The Microsoft Jet database engine uses the Xbase folder entries as follows:

Entry	Description
win32	The location of MSXB3032.DLL.  The full path name is determined at the time of installation (String).
NetworkAccess	An On or Off indicator for file locking preference.  If NetworkAccess is Off, tables are opened for exclusive access, regardless of the settings of the OpenDatabase and OpenRecordset methods' exclusive argument.  The default is On.
PageTimeout	The length of time between when data is placed in an internal cache and when it's invalidated.  The value is specified in 100 millisecond units.  The default is 600 units (60 seconds).
INFPath	The full path to the .INF file directory.  The Jet database engine first looks for an .INF file in the directory containing the table.  If the .INF file isn't in the database directory, it looks in the INFPath.  If there is no INFPath, it uses whatever index files (.CDX or .MDX) it finds in the database directory.  This entry is not written by default.
CollatingSequence	The collating sequence for all dBASE tables created or opened using Microsoft Jet.  Possible values are ASCII and International.  The default is ASCII.
DataCodePage	An indicator of how text pages are stored.  Possible settings are: OEM:  OemToAnsi and AnsiToOem conversions done.  This is the default. ANSI:  OemToAnsi and AnsiToOem conversions not done.
Deleted	An On or Off indicator that determines how records marked for deletion are handled by the Jet database engine.  On corresponds to the dBASE command SET DELETED ON and indicates never to retrieve or position on a deleted record.  Off corresponds to the dBASE command SET DELETED OFF and indicates to treat a deleted record like any other record.  The default is Off.
Century	An On or Off indicator for formatting the century component of dates in cases where date-to-string functions are used in index expressions.  On corresponds to the dBASE command SET CENTURY ON and Off corresponds to the dBASE command SET CENTURY OFF.  The default is Off.
Date	The date formatting style to use in cases where date-to-string functions are used in index expressions.  The possible settings for this entry, which corresponds to the dBASE SET DATE command, are American, ANSI, British, French, DMY, German, Italian, Japan, MDY, USA, and YMD.  The default is American.
Mark	The decimal value of the ASCII character used to separate date parts.  The default depends on the Date setting as follows: "/" (American, MDY) "." (ANSI) "/" (British, French, DMY) "." (German) "-" (Italian) "/" (Japan, YMD)  "-" (USA)
Exact	An On or Off indicator for string comparisons.  On corresponds to the dBASE command SET EXACT ON.  Off corresponds to the dBASE command SET EXACT OFF.  The default is Off.
dBASE ISAM Formats

The JET\3.0\ISAM FORMATS\DBASE III folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full pathname of .DLL; determined at Setup
Import Filter	String	dBASE III (*.DBF)
Export Filter	String	dBASE III (*.DBF)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	Yes
IndexFilter	String	dBASE Index (*.NDX)
CreateDBOnExport	Boolean	No
CanLink	Boolean	Yes
'

The JET\3.0\ISAM FORMATS\DBASE IV folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Import Filter	String	dBASE IV (*.DBF)
Export Filter	String	dBASE IV (*.DBF)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	Yes
IndexFilter	String	dBASE Index (*.NDX)
CreateDBOnExport	Boolean	No
CanLink	Boolean	Yes
The JET\3.0\ISAM FORMATS\DBASE 5.x folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Import Filter	String	dBASE 5 (*.DBF)
Import Filter	String	dBASE 5 (*.DBF)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	Yes
IndexFilter	String	dBASE Index (*.NDX)
CreateDBOnExport	Boolean	No
Note   When you change settings Windows registry settings, you must exit and then restart the database engine for the new settings to take effect.

dBASE Initialization Settings (Jet 2.5)

For Jet 2.5, the location of the ODBC driver engine is stored in the Windows Registry in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet20\InstallableISAM\ subkey.  The initialization settings are automatically set by default, but can be changed by creating a [dBASE ISAM] section of your application's <APPNAME>.INI file and inserting an entry with the new value.  The .INI filename you use is set by the DBEngine INIPath property.  Follow the format shown in the Example column below.  You can change the setting of any the following options:

Option	Description	Example
CollatingSequence	Sets the sort sequence the Microsoft Jet database engine uses when interacting with a FoxPro or dBASE database.   Valid settings: ASCII (U.S. only) or International (all other countries). The default is ASCII (U.S. only), International (all other countries).	CollatingSequence= International
Century	Specifies whether the Jet engine uses four-digit years in Date fields when interacting with a FoxPro or dBASE database.   Valid settings: On or Off (default).	Century=On
Date	Sets the convention the Jet engine uses for displaying dates when interacting with a FoxPro or dBASE database.   See your FoxPro or dBASE documentation for valid settings.	Date=American
Mark	Defines the character the Jet engine uses to separate months, days, and years in date displays when interacting with a FoxPro or dBASE database.   The setting is the ASCII decimal value of the mark character, in this example, the forward slash (/).	Mark=47
INFPath = path	In this entry, path is a valid path where the corresponding information (.INF) file can be written.  The Jet engine uses this file to keep track of information about indexes you specify for each FoxPro or dBASE file. Set this to a valid path if you want to import or attach a table from a FoxPro or dBASE database on a read-only drive (for example, a CD-ROM drive).	INFPath = C:\ACCESS\FOXPRO
Deleted	Specifies whether the Jet engine displays records marked for deletion when interacting with a FoxPro or dBASE database.   Valid settings: On (default) or Off.	Deleted=On


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing Lotus Database Settings

See Also

When you install the Lotus database driver, the set-up program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys for Jet 3.0.  For Jet 2.5, the initialization settings are in the VB.INI (or <APPNAME>.INI file).  The following sections describe initialization and ISAM Format settings for both the 16-bit (Jet 2.5) and 32-bit (Jet 3.0) Lotus database drivers.

Lotus Initialization Settings (Jet 3.0)

The JET\3.0\ENGINES\LOTUS folder includes initialization settings for the MSLT3032.DLL driver, used for external access to Lotus spreadsheets.  Typical settings for the entries under this heading are shown in the following example.

win32=<pathname>\MSLT3032.DLL

TypeGuessRows=8

ImportMixedTypes=Text

AppendBlankRows=4

FirstRowHasNames=Yes

The Microsoft Jet database engine uses the Lotus folder entries as follows:

Entry	Description
win32	The location of MSLT3032.DLL.  The full pathname is determined at the time of installation (String).
TypeGuessRows	The number of rows to be checked for the data type.  The data type is determined given the maximum number of kinds of data found.  If there is a tie, the data type is determined in the following order: Number, Currency, Date, Text, Long Text.  If data is encountered that does not match the data type guessed for the column, it is returned as a Null value.  On import, if a column has mixed data types, the entire column will be cast according to the ImportMixedTypes setting.
ImportMixedTypes	Can be set to MajorityType or Text (default).  If set to MajorityType, columns of mixed data types will be cast to the predominate data type on import.  If set to Text, columns of mixed data types will be cast to Text on import
AppendBlankRows	The number of blank rows to be appended to the end of a WK1, WK3, or WK4 worksheet before new data is added.  For example, if AppendBlankRows is set to 4, Microsoft Jet will append 4 blank rows to the end of the worksheet before appending rows that contain data.  Integer values for this setting can range from 0 to 16; the default is 0 (no additional rows appended).
FirstRowHasNames	Can be set to Yes or No.  Yes indicates that the first row of the table contains column names; during export column names are exported as the first row.  No indicates no column names in the first row; column names appear as numbers (F1, F2, F3, and so on).
Lotus ISAM Formats

The JET\3.0\ISAM FORMATS\LOTUS WK1 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full pathname of .DLL; determined at set up
Filter	String	Lotus WK1 (*.wk1;*.wks)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
CanAttach	Boolean	No
The JET\3.0\ISAM FORMATS\LOTUS WK3 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full pathname of .DLL; determined at set up
Filter	String	Lotus WK3 (*.wk3)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
CanAttach	Boolean	No
The JET\3.0\ISAM FORMATS\LOTUS WK4 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full pathname of .DLL; determined at set up
Filter	String	Lotus WK4 (*.WK4)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
CanAttach	Boolean	No
Note   When you change settings Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.

Lotus Initialization Settings (Jet 2.5)

For Jet 2.5, the location of the Lotus driver engine is stored in the Windows Registry in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet20\InstallableISAM\ subkey.  The initialization settings are automatically set by default, but can be changed by creating a [Lotus ISAM] section of your application's <APPNAME>.INI file and inserting an entry with the new value.  The .INI filename you use is set by the INIPath property of the DBEngine object.  Follow the format shown in the examples shown above.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing Microsoft Excel Settings

See Also

The Microsoft Excel database driver is available with Jet 3.0 only.  If you are creating a 16-bit (Jet 2.5) application, you will be unable to access the Excel driver.  When you install Visual Basic, the set-up program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys.  The following sections describe initialization and ISAM Format settings for the Microsoft Excel database driver.

Microsoft Excel Initialization Settings

The JET\3.0\ENGINES\EXCEL folder includes initialization settings for the MSXL3032.DLL driver, used for external access to Microsoft Excel worksheets.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSXL3032.DLL

TypeGuessRows=8

ImportMixedTypes=Text

AppendBlankRows=4

FirstRowHasNames=Yes

The Microsoft Jet database engine uses the Excel folder entries as follows:

Entry	Description
win32	The location of MSXL3032.DLL.  The full path name is determined at the time of installation (String).
TypeGuessRows	The number of rows to be checked for the data type.  The data type is determined given the maximum number of kinds of data found.  If there is a tie, the data type is determined in the following order: Number, Currency, Date, Text, Boolean.  If data is encountered that does not match the data type guessed for the column, it is returned as a Null value.  On import, if a column has mixed data types, the entire column will be cast according to the ImportMixedTypes setting.
ImportMixedTypes	Can be set to MajorityType or Text (default).  If set to MajorityType, columns of mixed data types will be cast to the predominate data type on import.  If set to Text, columns of mixed data types will be cast to Text on import
AppendBlankRows	The number of blank rows to be appended to the end of a Version 3.0 or Version 4.0 worksheet before new data is added.  For example, if AppendBlankRows is set to 4, Microsoft Jet will append 4 blank rows to the end of the worksheet before appending rows that contain data.  Integer values for this setting can range from 0 to 16; the default is 0 (no additional rows appended).
FirstRowHasNames	Can be set to Yes or No.  Yes indicates that the first row of the table contains column names; during export column names are exported as the first row.  No indicates no column names in the first row; column names appear as numbers (1, 2, 3, and so on).
Microsoft Excel ISAM Formats

The JET\3.0\ISAM FORMATS\EXCEL 3.0 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Microsoft Excel 3 (*.XLS)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
The JET\3.0\ISAM FORMATS\EXCEL 4.0 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Microsoft Excel 4 (*.XLS)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
The JET\3.0\ISAM FORMATS\EXCEL 5.0 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Microsoft Excel 5 (*.XLS)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
The JET\3.0\ISAM FORMATS\EXCEL 7.0 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Microsoft Excel 7 (*.XLS)
OneTablePerFile	Boolean	No
IsamType	Integer	1
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	Yes
Note   When you change settings Windows registry settings, you must exit and then restart the database engine for the new settings to take effect.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing Microsoft Foxpro Database Settings

See Also

When you install the Microsoft FoxPro database driver, the set up program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys for Jet 3.0.  For Jet 2.5, the initialization settings are in the VB.INI (or <APPNAME>.INI file).  The following sections describe initialization and ISAM Format settings for both the 16-bit (Jet 2.5) and 32-bit (Jet 3.0) FoxPro database drivers.

Microsoft FoxPro Initialization Settings (Jet 3.0)

The Jet\3.0\Engines\Xbase folder includes initialization settings for the MSXB3032.DLL driver, used for access to external FoxPro data sources.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSXB3032.DLL

NetworkAccess=On

PageTimeout=600

INFPath=C:\DBASE\SYSTEM

CollatingSequence=ASCII

DataCodePage=OEM

Deleted=Off

Century=Off

Date=American

Mark=47

Exact=Off

The Microsoft Jet database engine uses the Xbase folder entries as follows:

Entry	Description
win32	The location of MSXB3032.DLL.  The full path name is determined at the time of installation (String).
NetworkAccess	An On or Off indicator for file locking preference.  If NetworkAccess is Off, tables are opened for exclusive access, regardless of the settings of the OpenDatabase and OpenRecordset methods' exclusive argument.  The default is On.
PageTimeout	The length of time between when data is placed in an internal cache and when it's invalidated.  The value is specified in 100 millisecond units.  The default is 600 units (60 seconds).
INFPath	The full path to the .INF file directory.  The Jet database engine first looks for an .INF file in the directory containing the table.  If the .INF file isn't in the database directory, it looks in the INFPath.  If there is no INFPath, it uses whatever index files (.CDX or .MDX) it finds in the database directory.  This entry is not written by default.
CollatingSequence	The collating sequence for all FoxPro tables created or opened using the Microsoft Jet engine.  Possible values are ASCII and International.  The default is ASCII.
DataCodePage	An indicator of how text pages are stored.  Possible settings are: OEM:  OemToAnsi and AnsiToOem conversions done.  This is the default. ANSI:  OemToAnsi and AnsiToOem conversions not done.
Deleted	An On or Off indicator that determines how records marked for deletion are handled by the Jet database engine.  On corresponds to the FoxPro command SET DELETED ON and indicates never to retrieve or position on a deleted record.  Off corresponds to the FoxPro command SET DELETED OFF and indicates to treat a deleted record like any other record.  The default is Off.
Century	An On or Off indicator for formatting the century component of dates in cases where date-to-string functions are used in index expressions.  On corresponds to the FoxPro command SET CENTURY ON and Off corresponds to the FoxPro command SET CENTURY OFF.  The default is Off.
Date	The date formatting style to use in cases where date-to-string functions are used in index expressions.  The possible settings for this entry, which corresponds to the FoxPro SET DATE command, are American, ANSI, British, French, DMY, German, Italian, Japan, MDY, USA, and YMD.  The default is American.
Mark	The decimal value of the ASCII character used to separate date parts.  The default depends on the Date setting as follows: "/" (American, MDY) "." (ANSI) "/" (British, French, DMY) "." (German) "-" (Italian) "/" (Japan, YMD) "-" (USA)
Exact	An On or Off indicator for date comparisons.  On corresponds to the dBASE command SET EXACT ON.  Off corresponds to the dBASE command SET EXACT OFF.  The default is Off.
FoxPro ISAM Formats

The JET\3.0\ISAM FORMATS\FOXPRO 2.0 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	FoxPro 2.0 (*.DBF)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	Yes
IndexFilter	String	FoxPro Index (*.NDX)
CreateDBOnExport	Boolean	No
The JET\3.0\ISAM FORMATS\FOXPRO 2.5 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	FoxPro 2.5 (*.DBF)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	Yes
IndexFilter	String	FoxPro Index (*.NDX)
CreateDBOnExport	Boolean	No
The JET\3.0\ISAM FORMATS\FOXPRO 2.6 folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	FoxPro 2.6 (*.DBF)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	Yes
IndexFilter	String	FoxPro Index (*.NDX)
CreateDBOnExport	Boolean	No
Note   When you change settings Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.

FoxPro Initialization Settings (Jet 2.5)

For Jet 2.5, FoxPro uses the same driver and initialization settings as dBASE.  The location of the dBASE driver engine is stored in the Windows Registry in the HKEY_LOCAL_MACHINE\SOFTWARE \Microsoft\Jet20\InstallableISAM\ subkey.  The initialization settings are automatically set by default, but can be changed by creating a [dBASE ISAM] section of your application's <APPNAME>.INI file and inserting an entry with the new value.  The .INI filename you use is set by the DBEngine INIPath property.  Follow the format shown in the Example column below.  You can change the setting of any the following options:

Option	Description	Example
CollatingSequence	Sets the sort sequence the Microsoft Jet database engine uses when interacting with a FoxPro or dBASE database.   Valid settings: ASCII (U.S. only) or International (all other countries). The default is ASCII (U.S. only), International (all other countries).	CollatingSequence= International
Century	Specifies whether the Jet engine uses four-digit years in Date fields when interacting with a FoxPro or dBASE database.   Valid settings: On or Off (default).	Century=On
Date	Sets the convention the Jet engine uses for displaying dates when interacting with a FoxPro or dBASE database.   See your FoxPro or dBASE documentation for valid settings.	Date=American
Mark	Defines the character the Jet engine uses to separate months, days, and years in date displays when interacting with a FoxPro or dBASE database.   The setting is the ASCII decimal value of the mark character, in this example, the forward slash (/).	Mark=47
INFPath = path	In this entry, path is a valid path where the corresponding information (.INF) file can be written.  The Jet engine uses this file to keep track of information about indexes you specify for each FoxPro or dBASE file. Set this to a valid path if you want to import or attach a table from a FoxPro or dBASE database on a read-only drive (for example, a CD-ROM drive).	INFPath = C:\ACCESS\FOXPRO
Deleted	Specifies whether the Jet engine displays records marked for deletion when interacting with a FoxPro or dBASE database.   Valid settings: On (default) or Off.	Deleted=On


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing Microsoft Jet Engine ISAM Settings

See Also

When you install the Microsoft Jet Engine database driver, the set-up program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys, for Jet 3.0.  For Jet 2.5 the initialization settings are stored in the VB.INI or <APPNAME>.INI file, depending on how the IniPath property of the DBEngine object is set.  The following sections describe initialization and ISAM Format settings for both of the Jet engine database drivers.

Microsoft Jet Engine Initialization Settings (Jet 3.0)

The JET\3.0\ENGINES\JET folder contains initialization settings for the Microsoft Jet database engine.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSRD2X32.DLL

PageTimeout=5000

LockRetry=20

MaxBufferSize=

Threads=3

UserCommitSync=Yes

ImplicitCommitSync=No

ExclusiveAsyncDelay=2000

SharedAsyncDelay=0

SystemDB=<pathname>\System.MDB

The Jet database engine uses the following entries:

Entry	Description
win32	Location of the database engine driver (.DLL).  The pathname is determined at the time of installation (String).
PageTimeout	The length of time between when data that is not read-locked is placed in an internal cache and when it's invalidated, expressed in milliseconds.  The default is 5000 milliseconds (5 seconds) (Integer).
LockRetry	The number of times to repeat attempts to access a locked page before returning a lock conflict message.  The default is 20 times (Integer).
MaxBufferSize	The size of the database engine internal cache, measured in kilobytes (K).  MaxBufferSize must be an integer value greater that or equal to 18.  The default is no limit (Integer).
Threads	The number of background threads available to the Jet database engine.  The default is 3 (Integer).
UserCommitSync	Specifies whether the system waits for a commit to finish.  A value of Yes instructs the system to wait; a value of No instructs the system to perform the commit asynchronously.  The default is Yes (Boolean).
ImplicitCommitSync	Specifies whether the system waits for a commit to finish.  A value of No instructs the system to proceed without waiting for the commit to finish; a value of Yes instructs the system to wait for the commit to finish.  The default is No (Boolean).
ExclusiveAsyncDelay	Specifies the length of time, in milliseconds, to defer an asynchronous flush of an exclusive database.  The default value is 2000 (2 seconds) (Integer).
SharedAsyncDelay	Specifies the length of time, in milliseconds, to defer an asynchronous flush of a shared database.  The default value is 0 (Integer).
SystemDB	Specifies the full path name and filename of the system database.  The default is the appropriate path name followed by the filename SYSTEM.MDB (String).
Microsoft Jet Engine ISAM Formats

The JET\3.0\ISAM FORMATS\JET folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Microsoft Jet (*.MDB)
OneTablePerFile	Boolean	No
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	No
Note   When you change settings Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.

Microsoft Jet Engine Initialization Settings (Jet 2.5)

For Jet 2.5, the ISAM initialization settings are automatically set by default, but can be changed by creating an [ISAM] section of your application's <APPNAME>.INI file and inserting an entry with the new value.  The .INI filename you use is set by the DBEngine object's INIPath property.  Follow the format shown in the Example column below.  You can change the setting of any the following options:

Option	Description	Example
PageTimeout	Sets the length of time between when data that isn't being used is placed in an internal cache and when it's marked to be refreshed.  The settings are expressed in 100 millisecond units.  The default is 5 (500 milliseconds, or 0.5 seconds).	PageTimeout=5
LockedPageTimeout	Sets the length of time between when data that is being used is placed in an internal cache and when it's marked to be refreshed.  The settings are expressed in milliseconds.   The default is 5 (500 milliseconds, or 0.5 seconds).	LockedPageTimeout=5
CursorTimeout	Sets the cursor time-out in 1/10 second intervals.  The default is 5 (or 0.5 seconds).	CursorTimeout=5
LockRetry	Specifies the number of times to repeat attempts to access a locked page.   The default is 20.	LockRetry=20
CommitLockRetry	Specifies the number of times the Microsoft Jet database engine attempts to get a lock on data in order to save changes to data.  If it fails to get a commit lock, then updates are unsuccessful. The number of attempts the Jet engine makes to get a commit lock is directly related to the LockRetry entry.  For each attempt at getting a commit lock, it tries the number of times specified in the LockRetry setting to get a lock.  For example, if CommitLockRetry is 20 and LockRetry is 20, the Jet engine attempts to get a commit lock as many as 20 times, and for each of those times it tries to get a lock as many as 20 times, for a total of 400 attempts at locking. The default is 20.	CommitLockRetry=20
MaxBufferSize	The size of the Jet engine internal cache, measured in kilobytes (K).  MaxBufferSize must be between 18 and 4096.   Increasing this setting may provide better ODBC performance in systems with enough memory. The default is 512.	MaxBufferSize=512
ReadAheadPages	Sets the number of pages to read ahead when doing sequential scans.   The default is 16.	ReadAheadPages=16


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


Changing Paradox Database Settings

See Also

When you install the Paradox database driver, the Setup program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys for Jet 3.0.  For Jet 2.5, the initialization settings are in the VB.INI (or <APPNAME>.INI file).  The following sections describe initialization and ISAM Format settings for both the 16-bit (Jet 2.5) and 32-bit (Jet 3.0) Paradox database drivers.

Paradox Initialization Settings (Jet 3.0)

The JET\3.0\ENGINES\PARADOX folder includes initialization settings for the MSPX3032.DLL driver, used for access to external Paradox data.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSPX3032.DLL

PageTimeout=600

CollatingSequence=ASCII

DataCodePage=OEM

ParadoxUserName=Kimberly

ParadoxNetPath=P:\PDOXDB

ParadoxNetStyle=3.X

The Microsoft Jet database engine uses the Paradox folder entries as follows:

Entry	Description
win32	The location of MSPX3032.DLL.  The full path name is determined at the time of installation (String).
PageTimeout	The length of time between when data is placed in an internal cache and when it's invalidated.  The value is specified in 100 millisecond units.  The default is 600 units (60 seconds).
CollatingSequence	The collating sequence for all Paradox tables created or opened using Microsoft Jet.  Possible values are ASCII, International, Norwegian-Danish, and Swedish-Finnish.  The default is ASCII. Note that the CollatingSequence entry must match the collating sequence used when the Paradox table was built.
DataCodePage	An indicator of how text pages are stored.  Possible settings are: OEM:  OemToAnsi and AnsiToOem conversions done.  This is the default. ANSI:  OemToAnsi and AnsiToOem conversions not done.
ParadoxUserName	The name to be displayed by Paradox if a table is locked by the Paradox ISAM and an interactive user accessing the data from Paradox (rather than the ISAM) attempts to place an incompatible lock.  This entry isn't added if the computer isn't on a network.  The Setup program sets this to the Microsoft Jet user name. If you indicate a ParadoxUserName, you must also specify a ParadoxNetPath and a ParadoxNetStyle or you'll receive an error when trying to access external Paradox data.
ParadoxNetPath	The full path to the directory containing the PARADOX.NET file (for Paradox 3.x) or the PDOXUSRS.NET file (for Paradox 4.x).  This entry isn't added if the computer isn't on a network.  Usually, you need to change the initial setting (added by the set-up program), which is a best guess at where the file might be.  The full ParadoxNetPath (including the drive letter) must be consistent for all users sharing a particular database (directory). If you indicate a ParadoxNetPath, you must also specify a ParadoxUserName and a ParadoxNetStyle or you'll receive an error when trying to access external Paradox data.
ParadoxNetStyle	The network access style to use when accessing Paradox data.  Possible values are: 3.x 4.x (Note that Paradox 3.x users can't set this to 4.x or the driver will use the wrong locking method.  Paradox 5.0 users must use the 4.x ParadoxNetStyle setting to ensure proper locking behavior.) This entry isn't added if the computer isn't on a network.  This entry should correspond to whatever version of Paradox the users in the group are using.  It must be consistent for all users sharing a particular database (directory).  The default is 3.x. If you indicate a ParadoxNetStyle, you must also specify a ParadoxUserName and a ParadoxNetPath or you'll receive an error when trying to access external Paradox data.
Paradox ISAM Formats

The JET\3.0\ISAM FORMATS\PARADOX 3.x folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Paradox (*.DB)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	No
The JET\3.0\ISAM FORMATS\PARADOX 4.x folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Paradox (*.DB)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	No
The JET\3.0\ISAM FORMATS\PARADOX 5.x folder contains the following entries:

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Paradox (*.DB)
OneTablePerFile	Boolean	Yes
IsamType	Integer	0
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	No
Note   When you change settings Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.

Paradox Initialization Settings (Jet 2.5)

For Jet 2.5, the location of the Paradox driver engine is stored in the Windows registry in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet20\InstallableISAM\ subkey.  The initialization settings are automatically set by default, but can be changed by creating an [ODBC] section of your application's <APPNAME>.INI file and inserting an entry with the new value.  The .INI filename you use is set by the DBEngine INIPath property.  Follow the format shown in the Example column below.  You can change the setting of any the following options:

Option	Description	Example
ParadoxUserName	Sets the user name that Paradox uses to alert another user of a locking conflict. The default is the user name you specified when you installed Visual Basic.	ParadoxUserName=nancydav
ParadoxNetPath	Sets the path to your PARADOX locking file, either PARADOX.NET (for Paradox 3.X) or PDOXUSRS.NET (for Paradox 4.X) file. Set this option to a network path if you want to share Paradox locking settings with other users. The default is the directory where you installed your application.	ParadoxNetPath=F:\WRKGRP\
ParadoxNetStyle	Sets the Paradox Network Style, either 3.X (for the Paradox 3.X locking style) or 4.X (for the Paradox 4.X) locking style. This applies only to network users.  All users who share Paradox files on a network must have the same ParadoxNetStyle settings. The default is 3.X.	ParadoxNetStyle=3.X
CollatingSequence	Sets the sort sequence the Microsoft Jet database engine uses when interacting with a Paradox database. Valid settings: ASCII, International, Norwegian-Danish, or Swedish-Finnish. The default is ASCII (U.S. only).	CollatingSequence=International


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Text Data Source Settings


Changing Text Data Source Settings

See Also

When you install the Text Data Source database driver, the Setup program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys for Jet 3.0.  For Jet 2.5, the initialization settings are in the VB.INI (or <APPNAME>.INI file).  The following sections describe initialization and ISAM Format settings for both the 16-bit (Jet 2.5) and 32-bit (Jet 3.0) Text Data Source database drivers.

Text Data Source Initialization Settings (Jet 3.0)

The JET\3.0\ENGINES\TEXT folder includes initialization settings for the MSTX3032.DLL driver, used for external access to text data files.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\MSTX3032.DLL

MaxScanRows=25

FirstRowHasNames=False

CharacterSet=OEM

Format=TabDelimited

Extensions=none,asc,csv,tab,txt

ExportCurrencySymbols=Yes

The Microsoft Jet database engine uses the Text folder entries as follows:

Entry	Description
win32	The location of MSTX3032.DLL.  The full path name is determined at the time of installation (String).
MaxScanRows	The number of rows to be scanned when guessing the column types.  If set to 0, the entire file will be searched.
FirstRowHas Names	True or False, indicating whether the first record of data will be the column names
CharacterSet	Can be set to OEM or ANSI, indicating whether the source file is written using an OEM or ANSI code page.
Format	Can be any of the following: TabDelimited, CSVDelimited, Delimited(<single character >).  The single-character delimiter in the Delimited format can be any single character except a double quotation mark (").
Extensions	The extension of whatever files are to be browsed when looking for text-based data.
ExportCurrencySymbols	Yes (default) or no.  If set to Yes, the appropriate currency symbol is included when currency fields are exported (Boolean).
Text Data Source ISAM Formats

The JET\3.0\ISAM FORMATS\TEXT folder contains the following entries.

Entry Name	Type	Value
Engine	String	Full path name of .DLL; determined at set up
Filter	String	Text (*.TXT, *.CSV, *.TAB, *.ASC)
OneTablePerFile	Boolean	Yes
IsamType	Integer	2
IndexDialog	Boolean	No
CreateDBOnExport	Boolean	No
Note   When you change settings Windows Registry settings, you must exit and then restart the database engine for the new settings to take effect.

Text Data Source Initialization Settings (Jet 3.0)

You must customize your .INI file to include the [Text ISAM] heading and the type of text file.  The .INI filename you use is set by the DBEngine object's INIPath property.  The information entered into this section initializes the settings for the MSTX2016.DLL driver.  The following is an example of the heading and settings in the .INI file:

[Text ISAM]

Extensions=none,asc,csv,tab,txt

ColNameHeader=False

Format=TabDelimited

MaxScanRows=25

CharacterSet=OEM

Heading	Use for

Extensions	The name of the file extension for the text file.

ColNameHeader	True or False, indicating whether the first record of data is used for the column names.  Yes or no indicator.  Yes indicates that the first row of the table contains column names; during export column names are exported as the first row.  No indicates no column names in the first row; column names appear as numbers (1, 2, 3, and so on).

Format	TabDelimited, CSVDelimited, Delimited(<single character >), or FixedLength.  The single-character delimiter in the Delimited format can be any single character except a double quote (").

MaxScanRows	Number of rows to be scanned when guessing the column types.  If set to 0, the entire file is searched.

CharacterSet	OEM or ANSI, indicating whether the source file is written using an OEM or ANSI code page.


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Microsoft ODBC Settings

Changing Paradox Database Settings


Changing Microsoft ODBC Settings

See Also

When you install the Microsoft ODBC database driver, the set-up program writes a set of default values to the Windows registry in the Engines and ISAM Formats subkeys for Jet 3.0.  For Jet 2.5, the initialization settings are in the VB.INI (or <APPNAME>.INI file).  The following sections describe initialization and ISAM Format settings for both the 16-bit (Jet 2.5) and 32-bit (Jet 3.0) Microsoft ODBC database drivers.

Microsoft ODBC Driver Initialization Settings (Jet 3.0)

The JET\3.0\ENGINES\ODBC folder contains initialization settings for the Microsoft Jet database engine.  Typical settings for the entries in this folder are shown in the following example.

win32=<pathname>\ODBC32.DLL

LoginTimeout=20

QueryTimeout=60

ConnectionTimeout=600

AsyncRetryInterval=500

AttachCaseSensitive=0

AttachableObjects='TABLE','VIEW','SYSTEM TABLE','ALIAS','SYNONYM'

SnapshotOnly=0

TraceSQLMode=0

TraceODBCAPI=0

DisableAsync=0

JetTryAuth=1

PreparedInsert=0

PreparedUpdate=0

FastRequery=0

The Jet database engine uses the ODBC entries as follows:

Entry	Description
win32	The location of ODBC32.DLL.  The full path name is determined at the time of installation (String).
LoginTimeout	The number of seconds a log-in attempt can continue before timing out.  The default is 20.
QueryTimeout	The number of seconds a query can run (total processing time) before timing out.  The default is 60.
ConnectionTimeout	The number of seconds a cached connection can remain idle before timing out.  The default is 600.
AsyncRetryInterval	The number of milliseconds between polls to determine if the server is done processing a query.  This entry is used for asynchronous processing only.  The default is 500.
AttachCaseSensitive	An indicator of whether to match table names exactly when attaching.  Values are 0 (attach the first table matching the specified name, regardless of case) and 1 (attach a table only if the name matches exactly).  The default is 0.
AttachableObjects	A list of server object types to which attaching will be allowed.  The default is: 'TABLE', 'VIEW', 'SYSTEM TABLE', 'ALIAS', 'SYNONYM'.
SnapshotOnly	An indicator of whether Recordset objects are forced to be of snapshot type.  Values are 0 (allow dynasets) and 1 (force snapshots only).  The default is 0.
TraceSQLMode	An indicator of whether the Jet database engine will trace SQL statements sent to an ODBC data source in SQLOUT.TXT.  Values are 0 (no) and 1 (yes).  The default is 0.  This entry is interchangeable with SQLTraceMode.
TraceODBCAPI	An indicator of whether to trace ODBC API calls in ODBCAPI.TXT.  Values are 0 (no) and 1 (yes).  The default is 0.
DisableAsync	An indicator of whether to force synchronous query execution.  Values are 0 (use asynchronous query execution if possible) and 1 (force synchronous query execution).  The default is 0.
JetTryAuth	An indicator of whether to try using the Microsoft Access user name and password to log in to the server before prompting.  Values are 0 (no) and 1 (yes).  The default is 1.
PreparedInsert	An indicator of whether to use a prepared INSERT statement that inserts data in all columns.  Values are 0 (use a custom INSERT statement that inserts only non-Null values) and 1 (use a prepared INSERT statement).  The default is 0. Using prepared INSERT statements can cause Nulls to overwrite server defaults and can cause triggers to execute on columns that weren't inserted explicitly.
PreparedUpdate	An indicator of whether to use a prepared UPDATE statement that updates data in all columns.  Values are 0 (use a custom UPDATE statement that sets only columns that have changed) and 1 (use a prepared UPDATE statement).  The default is 0. Using prepared UPDATE statements can cause triggers to execute on unchanged columns.
FastRequery	An indicator of whether to use a prepared SELECT statement for parameterized queries.  Values are 0 (no) and 1 (yes).  The default is 0.
Microsoft ODBC Driver Initialization Settings (Jet 2.5)

For Jet 2.5, the location of the ODBC driver engine is stored in the Windows Registry in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet20\InstallableISAM\ subkey.  The initialization settings are automatically set by default, but can be changed by creating an [ODBC] section of your application's <APPNAME>.INI file and inserting an entry with the new value.  The .INI filename you use is set by the DBEngine object's INIPath property.  Follow the format shown in the Example column below.  You can change the setting of any the following options:

Option	Description	Example
QueryTimeout	Sets the number of seconds a query can be run before ODBC stops attempting to complete the query.  The countdown stops as soon as the first result record arrives from the server. The default is 60 seconds.	QueryTimeout=60
LoginTimeout	Sets the number of seconds a login attempt can continue before the Jet engine stops trying and displays a message.   The default is 20.	LoginTimeout=20
ConnectionTimeout	Sets the number of seconds a cached connection can remain idle before the Microsoft Jet database engine closes the connection.   The default is 600.  Be sure to use the Idle method of the DBEngine object to initialize this timer.	ConnectionTimeout=600
AsyncRetryInterval	Specifies in milliseconds the interval the Jet engine waits between polls that determine whether a server is finished processing an asynchronous query.   The default is 500.	AsyncRetryInterval=500
AttachCaseSensitive	Toggles case-sensitivity for matching table names. Valid settings: 0 Attach the first table whose name matches the specified string, regardless of case.   1 Attach a table only if its name exactly matches the specified string. The default is 0.	AttachCaseSensitive=0
AttachableObjects	Specifies a list of object types to which attaching is allowed.   Default values: 'TABLE', 'VIEW', 'SYSTEM TABLE', 'ALIAS', 'SYNONYM'.	AttachableObjects='TABLE','ALIAS'
TraceSQLMode	Indicates whether the Jet engine traces and records in the file SQLOUT.TXT all SQL statements sent to an ODBC data source.  This setting is interchangeable with SQLTraceMode. Valid settings: 0 (No) or 1 (Yes).  The default is 0.	TraceSQLMode=0 -Or- SQLTraceMode=0
TraceODBCAPI	Indicates whether the Jet engine traces and records in the file ODBCAPI.TXT all ODBC API calls.  If you set this to 1, it's recommended that you also set DisableAsync to 1. Valid settings: 0 (No) or 1 (Yes).  The default is 0.	TraceODBCAPI=0
DisableAsync	Indicates whether the Jet engine forces synchronous query execution. Valid settings:  0 Use asynchronous query execution where possible.   1 Force synchronous query execution.  This entry is ignored for Visual Basic and the default is 1 (synchronous).	DisableAsync=
TryJetAuth	Indicates whether to try using the Jet engine user name and password to log on to the server before prompting you to enter a user name and password. Valid settings: 0 (No) or 1 (Yes).  The default is 1.	TryJetAuth=1
PreparedInsert	Indicates whether the Jet engine uses a prepared INSERT that inserts data in all columns. Using a prepared INSERT can cause Nulls to replace server defaults, and can cause triggers to execute on columns where data wasn't inserted explicitly. Valid settings: 0 (Default)  Use a custom INSERT that inserts only non-Null values.   1 Use a prepared INSERT.	PreparedInsert=0
PreparedUpdate	Indicates whether the Jet engine uses a prepared UPDATE that updates data in all columns. Using a prepared UPDATE can cause triggers to execute on unchanged columns. Valid settings: 0 (Default)  Use a custom UPDATE that uses a SET only for columns that have changed.   1 Use a prepared UPDATE.	PreparedUpdate=0
FastRequery	Indicates whether to use a prepared SELECT for parameterized queries. Valid settings: 0 (Default)  Don't use a prepared SELECT for parameterized queries.  This is a bit slower but uses fewer connections.   1 Use a prepared SELECT for parameterized queries.  This is faster but may use more connections.	FastRequery=0
SnapshotOnly	Indicates whether recordsets are forced to be snapshots. Valid settings: 0 (Default)  Get index information when tables are attached so that dynasets are allowed.   1 Ignore index information when tables are attached so that only snapshots are allowed.  If you choose this setting, you aren't able to edit data.	SnapshotOnly=0


See Also

Accessing Data in a Btrieve Database

Accessing Data in a dBASE Database

Accessing Data in a Lotus Spreadsheet

Accessing Data in a Microsoft Excel Worksheet or Workbook

Accessing Data in a Microsoft FoxPro Database

Accessing Data in a Microsoft Jet Database

Accessing Data in a Paradox Database

Accessing Data in a Text Document

Accessing External Databases

Changing Btrieve Database Settings

Changing dBASE Database Settings

Changing Lotus Database Settings

Changing Microsoft Excel Settings

Changing Microsoft FoxPro Database Settings

Changing Microsoft Jet Engine ISAM Settings

Changing Paradox Database Settings

Changing Text Data Source Settings


What is Database Replication?

See Also

Database replication is the process of copying a database so that two or more copies stay synchronized in terms of data and objects.  Each copy of the database is called a replica, and each contains an identical set of tables, queries, forms, reports, macros, and modules.  Replicas that belong to the same replica set can exchange updates of data or replicated objects.  This exchange is called synchronization.

Applications

Database replication is useful for:

Sharing data among offices.

Sharing data among dispersed users.

Making server data more accessible.

Distributing application updates.

Backing up data.

Building Replication Into an Application

Replication functions can be handled entirely in code.  You begin by creating a Microsoft Jet database, as you would for any application, and then converting the database into a replicable form.  Prior to converting the database, you can designate which tables, queries, forms, reports, macros, or modules in the database you want to keep from being included in all subsequent replicas.

After the database has been replicated, you can make additional replicas for other users or computers.  Any new tables, queries, forms, reports, macros, or modules created at each replica remain at that replica.  However, you can make any of these objects replicable by changing the object's Replicable property.

After you have made additional replicas and started using them, you can synchronize changes to the replicas.  The Synchronize method allows you to merge the data changes made at one replica with changes made at other replicas in the set.  Synchronization also updates the other replicas with any changes made to the Design Master.  The Microsoft Jet database engine supports multiple masters for changing data but only a single master for changing the design of the database.  The synchronization process might produce a conflict between two replicas where users changed the same record.  You can resolve these conflicts by reviewing the system table that stores them or by writing a custom resolution program.

By default, the first replica in the set is the Design Master.  As user or system requirements change, you can move design-master status to another replica.  If you are unable to move the design-master status because the Design Master is damaged or corrupted, you can recover by making your own replica the Design Master.


See Also

Converting a Database Into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a ReplicableForm

Making a Replica the Design Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

Moving Design-Master Status to Another Replica

Resolving Synchronization Conflicts

Synchronizing Replicas


SELECT Statement (SQL)

See Also	Example

Instructs the Microsoft Jet database engine to return information from the database as a set of records.

Syntax

SELECT [predicate] { * | table.* | [table.]field1 [, [table.]field2[, ...]]}
[AS alias1 [, alias2 [, ...]]]
FROM tableexpression [, ...] [IN externaldatabase]
[WHERE... ]
[GROUP BY... ]
[HAVING... ]
[ORDER BY... ]
[WITH OWNERACCESS OPTION]

The SELECT statement has these parts:

Part	Description

predicate	One of the following predicates: ALL, DISTINCT, DISTINCTROW, or TOP.  You use the predicate to restrict the number of records returned.

*	Specifies all fields from the specified table(s) are selected.

table	The name of the table containing the fields from which records are selected.

field1, field2	The names of the fields to retrieve data from.  If you include more than one field, they are retrieved in the order listed.

alias1, alias2	The names to use as column headers instead of the original column names in table.

tableexpression	The name of the table or tables containing the data you want to retrieve.

externaldatabase	The name of the database containing the tables in tableexpression if not in the current database.

Remarks

To perform this operation, the Jet engine searches the specified table(s), extracts the chosen columns, selects rows that meet the criterion, sorts and/or groups the resulting rows into the order specified.

SELECT statements don't change data in the database.

You can use a SELECT statement in the SQL property of a QueryDef object, in the RecordSource property of a Data control, or as an argument for the OpenRecordset method.

SELECT is usually the first word in an SQL statement.  Most SQL statements are either SELECT or SELECT...INTO statements.

The minimum syntax for a SELECT statement is:

SELECT fields FROM table

You can use an asterisk (*) to select all fields in a table.  The following example selects all of the fields in the Employees table:

SELECT * FROM Employees;

If a field name is included in more than one table in the FROM clause, precede it with the table name and the . (dot) operator.  In the following example, the Department field is in both the Employees table and the Supervisors table.  The SQL statement selects Department from the Employees table and SupvName from the Supervisors table:

SELECT Employees.Department, SupvName
FROM Supervisors, Employees
WHERE Employees.Department = Supervisors.Department;

When a Recordset object is created, the Jet database engine uses the table's field name as the Field object name in the Recordset.  If you want a different field name or a name isn't implied by the expression used to generate the field, use the AS reserved word.  The following example uses the title Birth Date to name the returned Field in the resulting Recordset:

SELECT [Birth Date]
AS Birth FROM Employees;

Whenever you use aggregate functions or queries that return ambiguous or duplicate Field object names, you must use the AS clause to provide an alternate name for the Field.  The following example uses the title Head Count to name the returned Field in the resulting Recordset:

SELECT COUNT(EmployeeID)
AS [Head Count] FROM Employees;

You can use the other clauses in a SELECT statement to further restrict and organize your returned data.  For more information, see the Help topic for the clause you're working with.

In your Visual Basic program, you can also create a SELECT statement in your application by concatenating local variables into the statement as needed to select, sort, or filter the data as dictated by your application.  For example, if you have a TextBox control (TitleWanted) containing the name of a Title and you want to fetch all books from the Titles table with this title, you can create an SQL statement that includes the current value of the TextBox.  Note that the SQL query encloses the TitleWanted value in single quotation marks (' '):

Set Rst = Db.OpenRecordset("SELECT * FROM Titles " _
& " WHERE Title = '" & TitleWanted.Text & "'" )


See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL)

DELETE Statement (SQL)

FROM Clause (SQL)

GROUP BY Clause (SQL)

HAVING Clause (SQL)

IN Clause (SQL)

INSERT INTO Statement (SQL)

ORDER BY Clause (SQL)

Retrieving Data Using SQL

SELECT...INTO Statement (SQL)

SQL Aggregate Functions

UNION Operation (SQL)

UPDATE Statement (SQL)

WHERE Clause (SQL)

WITH OWNERACCESS OPTION Declaration (SQL)


SELECT Statement, FROM Clause Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT LastName, FirstName  FROM Employees;	Selects the LastName and FirstName fields of all records in the Employees table.
SELECT Employees.*  FROM Employees;	Selects all fields from the Employees table.
SELECT Count(PostalCode) AS Tally  FROM Customers;	Counts the number of records that have an entry in the PostalCode field and names the returned Field "Tally".
SELECT LastName, Salary AS Current, Salary * 1.1 AS Proposed  FROM Employees;	Shows what the salary would be if each employee received a 10 percent raise.  It doesn't change the original salary amounts.
SELECT LastName AS Name, Salary  FROM Employees;	Places the title Name at the top of the LastName column.  The title Salary is displayed at the top of the Salary column.
SELECT Count(*) AS [Total Employees], Avg(Salary)  AS [Average Salary], Max(Salary) AS [Maximum Salary]  FROM Employees;	Shows the number of employees and the average and maximum salaries.
SELECT LastName, 'has a salary of', Salary  FROM Employees;	For each record, shows the LastName and Salary in the first and last fields.  The string "has a salary of" is returned as the middle field of each record.


FROM Clause (SQL)

See Also

Specifies the tables or queries that contain the fields listed in the SELECT statement.

Syntax

SELECT fieldlist
FROM tableexpression [IN externaldatabase]

A SELECT statement containing a FROM clause has these parts:

Part	Description

fieldlist	The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.

tableexpression	An expression that identifies one or more tables from which data is retrieved.  The expression can be a single table name, a saved query name, or a compound resulting from an INNER JOIN or LEFT JOIN or RIGHT JOIN.

externaldatabase	The full pathname of an external database containing all the tables in tableexpression.

Remarks

FROM is required and follows any SELECT statement.

The order of the table names in tableexpression isn't important.

For improved performance and ease of use, it's recommended that you use an attached table instead of an IN clause to retrieve data from an external database.

The following example shows how you can retrieve data from the Employees table:

SELECT LastName, FirstName
FROM Employees;


See Also

IN Clause (SQL)

INNER JOIN Operation (SQL)

LEFT JOIN, RIGHT JOIN Operations (SQL)

Retrieving Data Using SQL

SQL Aggregate Functions

WHERE Clause (SQL)


IN Clause (SQL)

See Also	Example

Identifies tables in any external database to which the Microsoft Jet database engine can connect, such as a dBASE or Paradox database or an external Jet database.

Syntax

To identify a destination table:

[SELECT | INSERT] INTO destination IN
{path | ["path" "type"] | ["" [type; DATABASE = path]]}

To identify a source table:

FROM tableexpression IN
{path | ["path" "type"] | ["" [type; DATABASE = path]]}

A SELECT statement containing an IN clause has these parts:

Part	Description

destination	The name of the external table into which data is inserted.

tableexpression	The name of the table or tables from which data is retrieved.  This argument can be a single table name, a saved query, or a compound resulting from an INNER JOIN or LEFT JOIN or RIGHT JOIN.

path	The full path for the directory or file containing table.

      type	The name of the database type used to create table if a database isn't a Jet database (for example, dBASE III, dBASE IV, Paradox 3.x, Paradox 4.x, or Btrieve).

Remarks

You can use IN to connect to only one external database at a time.

In some cases, the path argument refers to the directory containing the database files.  For example, when working with dBASE, FoxPro or Paradox database tables, the path argument specifies the directory containing .DBF or .DB files.  The table filename is derived from the destination or tableexpression arguments.

To specify a non-Jet database, append a semicolon (;) to the name, and enclose it in single (' ') or double (" ") quotation marks.  For example, either 'dBASE IV;' or "dBASE IV;" is acceptable.

You can also use the DATABASE reserved word to specify the external database.  For example, the following lines specify the same table:

... FROM Table IN  "" [dBASE IV; DATABASE=C:\DBASE\DATA\SALES;];

... FROM Table IN "C:\DBASE\DATA\SALES" "dBASE IV;"

Notes

For improved performance and ease of use, use an attached table instead of IN.

You can also use the IN reserved word as a comparison operator in an expression.  For more information, see the In operator.


See Also

FROM Clause (SQL)

In Operator

INSERT INTO Statement (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

SQL Aggregate Functions


IN Clause Example

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.  The SQL statements shown below must be used as the SQL property of a QueryDef object, or in an SQL expression with the OpenRecordset method.

External database	SQL statement
Microsoft Jet database	SELECT CustomerID FROM Customers IN MYDATA.MDB  WHERE CustomerID Like "A*"; MYDATA.MDB is the name of the Jet database that contains the Customers table.
dBASE III or IV	SELECT [CustomerID] FROM Customer IN "C:\DBASE\DATA\SALES" "dBASE IV;" WHERE CustomerID Like "A*"; To retrieve data from a dBASE III table, substitute "dBASE III" in place of "dBASE IV;".
dBASE III or IV using DATABASE syntax	SELECT [CustomerID] FROM Customer IN "" [dBASE IV; DATABASE=C:\DBASE\DATA\SALES;]  WHERE CustomerID Like "A*"; To retrieve data from a dBASE III table, substitute "dBASE III" in place of "dBASE IV;".
Paradox 3.x or 4.x	SELECT [CustomerID] FROM Customer IN "C:\PARADOX\DATA\SALES" "Paradox 4.x;" WHERE CustomerID Like "A*"; To retrieve data from a Paradox version 3.x table, substitute "Paradox 3.x;" in place of "Paradox 4.x;".
Paradox 3.x or 4.x using DATABASE syntax	SELECT [CustomerID] FROM Customer IN "" [Paradox 4.x;DATABASE=C:\PARADOX\DATA\SALES;]  WHERE CustomerID Like "A*"; To retrieve data from a Paradox version 3.x table, substitute "Paradox 3.x;" in place of "Paradox 4.x;".
Btrieve	SELECT [CustomerID] FROM Customer IN "C:\BTRIEVE\DATA\SALES\FILE.DDF" "Btrieve;"  WHERE CustomerID Like "A*"; C:\BTRIEVE\DATA\SALES\FILE.DDF is the path and filename of the Btrieve data definition file.
Btrieve	SELECT [CustomerID] FROM Customers IN "" [Btrieve;DATABASE=C:\BTRIEVE\DATA\SALES\FILE.DDF;]  WHERE CustomerID Like "A*"; C:\BTRIEVE\DATA\SALES\FILE.DDF is the path and filename of the Btrieve data definition file.


WHERE Clause (SQL)

See Also	Example

Specifies which records from the tables listed in the FROM clause are affected by a SELECT, UPDATE, or DELETE statement.

Syntax

SELECT fieldlist
FROM tableexpression
WHERE criteria

A SELECT statement containing a WHERE clause has these parts:

Part	Description

fieldlist	The name of the field or fields to be retrieved along with any field-name aliases, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.

tableexpression	The name of the table or tables from which data is retrieved.

criteria	An expression that records must satisfy to be included in the query results.

Remarks

The Microsoft Jet database engine selects the records that meet the conditions listed in the WHERE clause.  If you don't specify a WHERE clause, your query returns all rows from the table.  If you specify more than one table in your query and you haven't included a WHERE clause or a JOIN clause, your query generates a Cartesian product of the tables.

WHERE is optional, but when included, follows FROM.  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).

If you don't use a JOIN clause to perform SQL join operations on multiple tables, the resulting Recordset won't be updatable.

WHERE is similar to HAVING.  WHERE determines which records are selected.  Similarly, once records are grouped with GROUP BY, HAVING determines which records are displayed.

Use the WHERE clause to eliminate records 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 employees whose salaries are more than $21,000:

SELECT LastName, Salary
FROM Employees
WHERE Salary > 21000;

A WHERE clause can contain up to 40 expressions linked by logical operators, such as And and Or.

When you enter a field name that contains a space or punctuation, surround the name with brackets ([ ]):

SELECT ProductID, [Units In Stock]
FROM Products
WHERE [Units In Stock] <= [Reorder Level];

When you specify the criteria argument, date literals must be in U.S. format, even if you're not using the U.S. version of the Jet database engine.  For example, May 10, 1994, is written 10/5/94 in the United Kingdom and 5/10/94 in the United States.  Be sure to enclose your date literals with the number sign (#) as shown in the following examples.

To find records dated May 10, 1994 in a United Kingdom database, you must use the following SQL statement:

SELECT *
FROM Orders
WHERE ShippedDate = #5/10/94#;

You can also use the DateValue function which is aware of the International settings established by Microsoft Windows.  For example, for code in the United States:

SELECT *
FROM Orders
WHERE ShippedDate = DateValue('5/10/94');

For code in the United Kingdom:

SELECT *
FROM Orders
WHERE ShippedDate = DateValue('10/5/94');


See Also

IN Clause (SQL)

ORDER BY Clause (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

SQL Aggregate Functions


WHERE Clause Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT LastName, FirstName  FROM Employees  WHERE LastName = 'King';	Selects the LastName and FirstName fields of each record in which the last name is King.
SELECT LastName, FirstName  FROM Employees  WHERE LastName Like 'S*';	Selects the LastName and FirstName fields for employees whose last names begin with the letter S.
SELECT LastName, Salary  FROM Employees  WHERE Salary Between 20000 And 30000;	Selects employees whose salaries are between $20,000 and $30,000, inclusive.
SELECT LastName, Salary  FROM Employees  WHERE LastName Between 'Lon' And 'Tol';	Selects employees whose last names fall in alphabetic order between Lon and Tol, inclusive.  It doesn't retrieve Tolstoy because Tolstoy follows Tol and therefore is outside the specified range.
SELECT OrderID, OrderDate  FROM Orders  WHERE OrderDate Between #1-1-94# And #6-30-94#;	Selects orders placed during the first half of 1994.
SELECT LastName, FirstName, City  FROM Employees  WHERE City In ('Interlaken', 'New York', 'Frankfurt');	Selects employees who live in Interlaken, New York, or Frankfurt.


GROUP BY Clause (SQL)

See Also	Example

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 SQL aggregate function, such as Sum or Count, in the SELECT statement.

Syntax

SELECT fieldlist
FROM table
WHERE criteria
GROUP BY groupfieldlist

A SELECT statement containing a GROUP BY clause has these parts:

Part	Description

fieldlist	The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.

table	The name of the table from which records are retrieved.  For more information, see the FROM clause.

criteria	Selection criteria.  If the statement includes a WHERE clause, the Microsoft Jet database engine groups values after applying the WHERE conditions to the records.

groupfieldlist	The names of up to 10 fields used to group records.  The order of the field names in groupfieldlist determines the grouping levels from the highest to the lowest level of grouping.

Remarks

GROUP BY is optional.

Summary values are omitted if there is no SQL aggregate function in the SELECT statement.

Null values in GROUP BY fields are grouped and aren't omitted.  However, Null values aren't evaluated in any SQL aggregate function.

Use the WHERE clause to exclude rows you don't want grouped, and use the HAVING clause to filter records after they've been grouped.

Unless it contains Memo or OLE Object data, a field in the GROUP BY field list can refer to any table's field in the FROM clause, even if the field isn't included in the SELECT statement, provided the SELECT statement includes at least one SQL aggregate function.  The Jet database engine can't group on Memo or OLE Object fields.

All fields in the SELECT field list must either be included in the GROUP BY clause or be included as arguments to an SQL aggregate function.

When you enter a field name that contains a space or punctuation, surround the name with brackets ([ ]):

SELECT [CategoryID],
Sum([Units in Stock])
FROM Products
GROUP BY [CategoryID];


See Also

HAVING Clause (SQL)

ORDER BY Clause (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

SQL Aggregate Functions


GROUP BY Clause Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT Department, Count([Department]) AS Tally  FROM Employees  GROUP BY Department;	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 Department = 'Sales'  GROUP BY Title;	For each unique job title, calculates the number of Sales department employees who have that 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)

See Also	Example

Specifies which grouped records are displayed in a SELECT statement with a GROUP BY clause.  Once GROUP BY combines records, HAVING displays any records grouped by the GROUP BY clause that satisfy the conditions of the HAVING clause.

Syntax

SELECT fieldlist
FROM table
WHERE selectcriteria
GROUP BY groupfieldlist
HAVING groupcriteria

A SELECT statement containing a HAVING clause has these parts:

Part	Description

fieldlist	The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.

table	The name of the table from which records are retrieved.  For more information, see the FROM clause.

selectcriteria	Selection criteria.  If the statement includes a WHERE clause, The Microsoft Jet database engine groups values after applying the WHERE conditions to the records.

groupfieldlist	The names of up to 10 fields used to group records.  The order of the field names in groupfieldlist determines the grouping levels from the highest to the lowest level of grouping.

groupcriteria	An expression that determines which grouped records to display.

Remarks

HAVING is optional.

HAVING is similar to WHERE, which determines which records are selected.  Once records are grouped with GROUP BY, HAVING determines which records are displayed:

SELECT [CategoryID],
Sum([Units in Stock])
FROM Products
GROUP BY [CategoryID]
HAVING Sum([Units in Stock]) > 100 AND ProductName LIKE "BOS*";

A HAVING clause can contain up to 40 expressions linked by logical operators, such as And and Or.


See Also

GROUP BY Clause (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

SQL Aggregate Functions


HAVING Clause Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT Title, Count([Title])  FROM Employees  WHERE Department = 'Production'  GROUP BY Title  HAVING Count(Title) > 50;	Selects 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;	Selects departments with more than 100 employees.


ORDER BY Clause (SQL)

See Also	Example

Sorts a query's resulting records on a specified field or fields in ascending or descending order.

Syntax

SELECT fieldlist
FROM table
WHERE selectcriteria
ORDER BY field1 [ASC | DESC ][, field2 [ASC | DESC ][, ...]]

A SELECT statement containing an ORDER BY clause has these parts:

Part	Description

fieldlist	The name of the field or fields to be retrieved along with any field-name aliases, SQL aggregate functions, selection predicates (ALL, DISTINCT, DISTINCTROW, or TOP), or other SELECT statement options.

table	The name of the table from which records are retrieved.  For more information, see the FROM clause.

selectcriteria	Selection criteria.  If the statement includes a WHERE clause, The Microsoft Jet database engine orders values after applying the WHERE conditions to the records.

field1, field2	The names of the fields on which to sort records.

Remarks

ORDER BY is optional.  If you don't include ORDER BY, the data is displayed 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 field you want to sort in ascending order.  Both of the following examples sort employee names in last name order:

SELECT LastName, FirstName
FROM Employees
ORDER BY LastName;

SELECT LastName, FirstName
FROM Employees
ORDER BY LastName ASC;

To sort in descending order (Z-A, 9-0), add the DESC reserved word to the end of each field you want to sort in descending order.  The following example selects salaries and sorts them in descending order:

SELECT LastName, Salary
FROM Employees
ORDER BY Salary DESC, LastName;

If you specify a field containing Memo or OLE Object data in the ORDER BY clause, an error occurs.  The Microsoft Jet database engine doesn't sort on fields of these types.

ORDER BY is usually the last item in an SQL statement.

You can include additional fields in the ORDER BY clause.  Records are sorted first by the first field listed after ORDER BY.  Records that have equal values in that field are then sorted by the value in the second field listed, and so on.


See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL)

GROUP BY Clause (SQL)

HAVING Clause (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

SQL Aggregate Functions


ORDER BY Clause Example

The SQL statements shown below use the ORDER BY clause to sort records alphabetically and then by category.

SQL statement	Description
SELECT LastName, FirstName  FROM Employees  ORDER BY LastName DESC;	Sorts the records by last name in descending order (Z-A).
SELECT CategoryID, ProductName, UnitPrice  FROM Products  ORDER BY CategoryID, ProductName;	Sorts by category ID first, then by product name.


ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL)

See Also	Example

Specifies records selected with SQL queries.

Syntax

SELECT [ALL | DISTINCT | DISTINCTROW | [TOP n [PERCENT]]]
FROM table

A SELECT statement containing these predicates has the following parts:

Part	Description
ALL	Assumed if you don't include one of the predicates.  The Microsoft Jet database engine selects all of the records that meet the conditions in the SQL statement.  The following two examples are equivalent and return all records from the Employees table: SELECT ALL * FROM Employees ORDER BY EmployeeID; SELECT * FROM Employees ORDER BY EmployeeID;
DISTINCT	Omits records that contain duplicate data in the selected fields.  To be included 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 LastName field, the following SQL statement returns only one of the records: SELECT DISTINCT LastName FROM Employees; If you omit DISTINCT, this query returns both Smith records. If the SELECT clause contains more than one field, the combination of values from all fields must be unique for a given record to be included in the results. The output of a query that uses DISTINCT isn't updatable and doesn't reflect subsequent changes made by other users.
DISTINCTROW	Omits data based on entire duplicate records, not just duplicate fields.  For example, you could create a query that joins the Customers and Orders tables on the CustomerID field.  The Customers table contains no duplicate CustomerID 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 CompanyName FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY CompanyName; 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, or if you output fields from all tables.
TOP	Returns a certain number of records that fall at the top or the bottom of a range specified by an ORDER BY clause.  Suppose you want the names of the top 25 students from the class of 1994: SELECT TOP 25 FirstName, LastName FROM Students WHERE [Graduation Year] = 1994 ORDER BY [Grade Point Average] DESC; If you don't include the ORDER BY clause, the query will return an arbitrary set of 25 records from the Students table that satisfy the WHERE clause. The TOP predicate doesn't choose between equal values.  In the preceding example, if the twenty-fifth and twenty-sixth highest grade point averages are the same, the query will return 26 records. You can also use the PERCENT reserved word to return a certain percentage of records that fall at the top or the bottom of a range specified by an ORDER BY clause.  Suppose that, instead of the top 25 students, you want the top 10 percent of the class: SELECT TOP 10 PERCENT FirstName, LastName FROM Students WHERE [Graduation Year] = 1994 ORDER BY [Grade Point Average] DESC; The value that follows TOP must be an unsigned Integer. TOP doesn't affect the query's updatability.
table	The name of the table from which records are retrieved.


See Also

Retrieving Data Using SQL


ALL, DISTINCT, DISTINCTROW, TOP Predicates Example

The following examples use two tables, Customers and Orders.

Customers Table

FirstName	CustomerID

Bob	1

Adam	2

Beverly	3

Bob	4

Orders Table

CustomerID	OrderID

1	1

1	2

2	3

2	4

2	5

4	6

4	7

The SQL statements shown below must be used as the SQL property of a QueryDef object or in a SQL expression with the OpenRecordset method.

SQL statement	Result	Updatable
SELECT ALL FirstName  FROM Customers INNER JOIN Orders  ON Customers.CustomerID = Orders.CustomerID;	Bob Bob Adam Adam Adam Bob Bob	Yes
SELECT DISTINCT FirstName  FROM Customers INNER JOIN Orders  ON Customers.CustomerID = Orders.CustomerID;	Bob Adam	No
SELECT DISTINCTROW FirstName  FROM Customers INNER JOIN Orders  ON Customers.CustomerID = Orders.CustomerID;	Bob Adam Bob	Yes
SELECT TOP 5 FirstName  FROM Customers INNER JOIN Orders  ON Customers.CustomerID = Orders.CustomerID ORDER BY Orders.OrderID	Bob Bob Adam Adam Adam	Yes


DELETE Statement (SQL)

See Also	Example

Creates a delete query that removes records from one or more of the tables listed in the FROM clause that satisfy the WHERE clause.

Syntax

DELETE [table.*]
FROM tableexpression
WHERE criteria

The DELETE statement has these parts:

Part	Description

table	The optional name of the table from which records are deleted.

tableexpression	The name of the table or tables from which records are deleted.  This argument can be a single table name or a compound resulting from an INNER JOIN, LEFT JOIN, or RIGHTJOIN operation.

criteria	An expression that determines which records to delete.

Remarks

DELETE is especially useful when you want to delete many records.

In a multiple-table DELETE statement, you must include the table argument.  If you specify more than one table to delete records from, they must all be many-only tables.

If you want to delete all of the records in a table, deleting the table itself is more efficient than running a delete query.  You can use the Execute method with a DROP TABLE statement to drop a table from the database.  If you delete the table, however, the structure is lost.  In contrast, when you use DELETE, only the data is deleted; the table structure and all of the table properties, such as field attributes and indexes, remain intact.

You can use DELETE to remove records from a single table or from the many side of a one-to-many relationship.  Cascade delete operations in a query only delete from the many side of a relationship.  For example, in the relationship between the Customers and Orders tables, the Orders table is the many side, so cascade delete operations would only affect the Orders table.

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 Null.

Important

Once you remove records using a delete query, you can't undo the operation.  If you want to know which records were deleted, first examine the results of a select query that uses the same criteria, and then run 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.


See Also

DROP Statement (SQL)

FROM Clause (SQL)

IN Clause (SQL)

INNER JOIN Operation (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

UPDATE Statement (SQL)

WHERE Clause (SQL)


DELETE Statement Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

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 Employees.*  FROM Employees INNER JOIN Payroll  ON Employees.EmployeeID = Payroll.EmployeeID  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.


INNER JOIN Operation (SQL)

See Also	Example

Combines records from two tables whenever there are matching values in a common field.

Syntax

FROM table1 INNER JOIN table2 ON table1.field1 compopr table2.field2

The INNER JOIN operation has these parts:

Part	Description

table1, table2	The names of the tables from which records are combined.

field1, field2	The names of the fields that are joined.  If they aren't numeric, 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.

compopr	Any relational comparison operator: "=," "<," ">," "<=," ">=," or "<>."

Remarks

You can use an INNER JOIN operation in any FROM clause.  It creates 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.

You can 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 aren't assigned to a department), you can use a LEFT JOIN or RIGHT JOIN operation to create an outer join.

If you try to join fields containing Memo or OLE Object data, an error occurs.

You can join any two numeric fields, even if they are of different data types.  For example, you can join a Number field, for which the Size property of its Field object is set to Integer, and a Counter field.

The following example shows how you could join the Categories and Products tables on the CategoryID field:

SELECT [Category Name], ProductName
FROM Categories INNER JOIN Products
ON Categories.CategoryID = Products.CategoryID;

In the preceding example, CategoryID is the joined field, but it isn't included in the query output because it isn't included in the SELECT statement.  To include the joined field, include the field name in the SELECT statement [image] in this case, Categories.CategoryID.

You can also link several ON clauses in a JOIN statement, using the following syntax:

SELECT fields
FROM table1 INNER JOIN table2
ON table1.field1 compopr table2.field1 AND
ON table1.field2 compopr table2.field2) OR
ON table1.field3 compopr table2.field3)];

You can also nest JOIN statements using the following syntax:

SELECT fields
FROM table1 INNER JOIN
(table2 INNER JOIN [( ]table3
[INNER JOIN [( ]tablex [INNER JOIN ...)]
ON table3.field3 compopr tablex.fieldx)]
ON table2.field2 compopr table3.field3)
ON table1.field1 compopr table2.field2;

A LEFT JOIN or a RIGHT JOIN may be nested inside an INNER JOIN, but an INNER JOIN may not be nested inside a LEFT JOIN or a RIGHT JOIN.


INNER JOIN Operation Example

The SQL statement shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT DISTINCTROW  Sum(UnitPrice * [Quantity]) AS [Sales],  FirstName & " " & LastName AS Name  FROM Employees INNER JOIN (Orders INNER JOIN OrderDetails  ON Orders.OrderID = OrderDetails.OrderID)  ON Employees.EmployeeID = Orders.EmployeeID  GROUP BY FirstName & " " & LastName;	Creates two equi-joins: one between the OrderDetails 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 OrderDetails table doesn't contain employee data.  The query produces a list of employees and their total sales.


See Also

LEFT JOIN, RIGHT JOIN Operations (SQL)

TRANSFORM Statement (SQL)

UNION Operation (SQL)


INSERT INTO Statement (SQL)

See Also	Example

Adds a record to a table.  This is referred to as an append query.

Syntax

Multiple-record append query:

INSERT INTO target [IN externaldatabase] [(field1[, field2[, ...]])]
SELECT [source.]field1[, field2[, ...]
FROM tableexpression

Single-record append query:

INSERT INTO target [(field1[, field2[, ...]])]
VALUES (value1[, value2[, ...])

The INSERT INTO statement has these parts:

Part	Description

target	The name of the table or query to append records to.

externaldatabase	The path to an external database.  For a description of the path, see the IN clause.

source	The name of the table or query to copy records from.

field1, field2	Names of the fields to append data to, if following a target argument, or the names of fields to obtain data from, if following a source argument.

tableexpression	The name of the table or tables from which records are inserted.   This argument can be a single table name or a compound resulting in an INNER JOIN, LEFT JOIN, or RIGHT JOIN operation or a saved query.

value1, value2	The values to insert into the specific fields of the new record.  Each value is inserted into the field that corresponds to the value's position in the list: value1 is inserted into field1 of the new record, value2 into field2, and so on.  You must separate values with a comma, and enclose text fields in double quotation marks (" ").

Remarks

You can use the INSERT INTO statement to add a single record to a table using the single-record append query syntax as shown above.  In this case, your code specifies the name and value for each field of the record.  You must specify each of the fields of the record that a value is to be assigned to and a value for that field.  When you don't specify each field, the default value or Null is inserted for missing columns.  Records are added to the end of the table.

You can also use INSERT INTO to append a set of records from another table or query by using the SELECT ... FROM clause as shown above in the multiple-record append query syntax.  In this case, the SELECT clause specifies the fields to append to the target table specified.

The source or target table may specify a table or a query.  If a query is specified, the Microsoft Jet database engine appends to any and all tables specified by the query.

INSERT INTO is optional but when included, precedes the SELECT statement.

If your destination table contains a primary key, make sure you append unique, non-Null values to the primary key field or fields; if you don't, the Jet engine won't append the records.

If you append records to a table with a Counter field, don't include the Counter field in your query.

Use the IN clause to append records to a table in another database.

To create a new table, use the SELECT... INTO statement instead to create a make-table query.

To find out which records will be appended before you run the append query, first execute and view the results of a select query that uses the same selection criteria.

An append query copies records from one or more tables to another.  The tables that contain the records you append aren't affected by the append query.

Instead of appending existing records from another table, you can specify the value for each field in a single new record using the VALUES clause.  If you omit the field list, the VALUES clause must include a value for every field in the table; otherwise, the INSERT will fail.  Use an additional INSERT INTO statement with a VALUES clause for each additional record you want to create.


See Also

FROM Clause (SQL)

Retrieving Data Using SQL

WHERE Clause (SQL)


INSERT INTO Statement Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
INSERT INTO Customers  SELECT [New Customers].*  FROM [New Customers];	Selects all records in a hypothetical New Customers table and adds them to the Customers table. (When individual columns are not designated, the SELECT table column names must match exactly those in the INSERT INTO table.)
INSERT INTO Employees (FirstName, LastName, Title)  VALUES ("Harry", "Washington", "Trainee");	Creates a new record in the Employees table.
INSERT INTO Employees  SELECT Trainees.*  FROM Trainees  WHERE HireDate < 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)

See Also	Example

Combines source-table records when used in any FROM clause.

Syntax

FROM table1 [ LEFT | RIGHT ] JOIN table2
ON table1.field1 compopr table2.field2

The LEFT JOIN and RIGHT JOIN operations have these parts:

Part	Description

table1, table2	The names of the tables from which records are combined.

field1, field2	The names of the fields that are joined.  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.

compopr	Any relational comparison operator: "=," "<," ">," "<=," ">=," or "<>."

Remarks

Use a LEFT JOIN operation to create a left outer join.  Left outer 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 outer join.  Right outer 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 could 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.

The following example shows how you could join the Categories and Products tables on the CategoryID field.  The query produces a list of all categories, including those that contain no products:

SELECT [Category Name],

ProductName

FROM Categories LEFT JOIN Products

ON Categories.CategoryID = Products.CategoryID;

In this example, CategoryID is the joined field, but it isn't included in the query results 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, Categories.CategoryID.

Notes

To create a query that includes only records in which the data in the joined fields is the same, use an INNER JOIN operation.

You can nest INNER, RIGHT, and LEFT joins.  See the discussion of nesting in the INNER JOIN topic to see how to nest joins of any type within other joins.

If you try to join fields containing Memo or OLE Object data, an error occurs.


LEFT JOIN, RIGHT JOIN Operations Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT [Department Name],  FirstName & " " & LastName AS Name  FROM Departments LEFT JOIN Employees  ON Departments.[Department ID] = Employees.[Department ID]  ORDER BY [Department Name];	Selects all departments, including those without employees.
SELECT LastName & ", " & FirstName AS Name,  [Department Name]  FROM Departments RIGHT JOIN Employees  ON Departments.[Department ID] = Employees.[Department ID]  ORDER BY LastName & ", " & FirstName;	Selects all employees, including those not assigned to a department.


See Also

INNER JOIN Operation (SQL)

UNION Operation (SQL)


PARAMETERS Declaration (SQL)

See Also	Example

Declares the name and data type of each parameter in a parameter query.

Syntax

PARAMETERS name datatype [, name datatype [, ...]]

The PARAMETERS declaration has these parts:

Part	Description

name	The name of the parameter.  Assigned to the Name property of the Parameter object and used to identify this parameter in the Parameters collection.  You can use name as a string that is displayed in a dialog box while your application runs the query.  Use brackets ([ ]) to enclose text that contains spaces or punctuation.  For example, [Low price] and [Begin report with which month?] are valid name arguments.

datatype	The parameter's data type.

Remarks

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, your code will need to provide the parameters each time the query is run.

The PARAMETERS declaration is optional but when included precedes any other statement, including SELECT.

If the declaration includes more than one parameter, separate them with commas.  The following example includes two parameters:

PARAMETERS [Low price] Currency, [Beginning date] DateTime;

You can use name but not datatype in a WHERE or HAVING clause.  The following example expects two parameters to be provided and then applies the criteria to records in the Orders table:

PARAMETERS [Low price] Currency,
[Beginning date] DateTime;
SELECT OrderID, [Order Amount]
FROM Orders
WHERE [Order Amount] > [Low price]
AND OrderDate >= [Beginning date];

The following example shows how to use parameters in your Visual Basic program:

Dim SQL As String, Qd as QueryDef, Rs as Recordset

SQL = "PARAMETERS [Low price] Currency, " _
& " 	[Beginning date] DateTime; " _
& " 	SELECT OrderID, [Order Amount] " _
& " 	FROM Orders " _
& " 	WHERE [Order Amount] > [Low price] " _
& " 	AND OrderDate >= [Beginning date];"

Set Qd = Db.CreateQueryDef("MyParameterQuery", SQL)

Qd.Parameters![Low Price] = 1.99

Qd.Parameters![Beginning date] = "#12/31/95#"

Set Rs = Qd.OpenRecordset()


See Also

Creating a Parameter Query


PARAMETERS Declaration Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
PARAMETERS [Enter a LastName:] Text;  SELECT *  FROM Employees  WHERE LastName =  [Enter a LastName:];	Requires you to provide an employee's last name and then uses that entry as the criteria for the query.
PARAMETERS [Enter a CategoryID:] Value;  SELECT DISTINCTROW  CategoryID, ProductName,  Count(OrderDetails.OrderID) AS Tally  FROM Products INNER JOIN OrderDetails  ON Products.ProductID = OrderDetails.ProductID  GROUP BY CategoryID, ProductName  HAVING CategoryID = [Enter a CategoryID:];	Requires you to provide a category ID and then uses that entry as the criteria for the query.


PROCEDURE Clause (SQL Only)

See Also	Example

Defines the name and optional parameters for a query.

Syntax

PROCEDURE name [param1 datatype[, param2 datatype[, ...]]

The PROCEDURE clause has these parts:

Part	Description

name	A name for the procedure.  It must follow standard naming conventions.

param1, param2	One or more field names or parameters.  For example:

PROCEDURE Sales_By_Country [Beginning Date] DateTime, [Ending Date] DateTime;

For more information on parameters, see PARAMETERS.

datatype	One of the 13 primary Microsoft Jet SQL data types or their synonyms.

Remarks

An SQL procedure consists of a PROCEDURE clause (which specifies the name of the procedure), an optional list of parameter definitions, and a single SQL statement.  For example, the procedure Get_Part_Number might run a query that retrieves a specified part number.

Notes

If the clause includes more than one field definition (that is, param-datatype pairs), separate them with commas.

The PROCEDURE clause must be followed by an SQL statement (for example, a SELECT or UPDATE statement).


See Also

Creating a Parameter Query


PROCEDURE Clause Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
PROCEDURE Category_List;  SELECT DISTINCTROW  [Category Name], CategoryID  FROM Categories  ORDER BY [Category Name];	Names the query Category_List.
PROCEDURE Summary  [Beginning Date] DATETIME,  [Ending Date] DATETIME;  SELECT DISTINCTROW  ShippedDate, OrderID, EmployeeID,  Format(ShippedDate, "yyyy") AS Year  FROM Orders  WHERE ShippedDate  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;


SELECT...INTO Statement (SQL)

See Also	Example

Creates a make-table query.

Syntax

SELECT field1[, field2[, ...]] INTO newtable [IN externaldatabase]
FROM source

The SELECT...INTO statement has these parts:

Part	Description

field1, field2	The name of the fields to be copied into the new table.

newtable	The name of the table to be created.  It must conform to standard naming conventions.  If newtable is the same as the name of an existing table, a trappable error will result.

externaldatabase	The path to an external database.  For a description of the path, see the IN clause.

source	The name of the existing table from which records are selected.  This can be either a single table or a query.

Remarks

You can use make-table queries to archive records, make backup copies of your tables, or make copies to export to another database or to use as a basis for reports that display data for a particular time period.  For example, you could produce a Monthly Sales by Region report by running the same make-table query each month.

Notes

You may want to define a primary key 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.

To add data to an existing table, use the INSERT INTO statement instead to create an append query.

To find out which records will be selected before you run the make-table query, first examine the results of the SELECT statement  that uses the same selection criteria.


See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL)

FROM Clause (SQL)

IN Clause (SQL)

Retrieving Data Using SQL

SELECT Statement (SQL)

UNION Operation (SQL)

WHERE Clause (SQL)


SELECT...INTO Statement Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

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.FirstName, LastName INTO Trainees FROM Employees  WHERE Title = 'Trainee';	Creates a new table called Trainees 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 INNER JOIN Payroll  ON Employees.EmployeeID = Payroll.EmployeeID  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.


TRANSFORM Statement (SQL)

See Also	Example

Creates a crosstab query.

Syntax

TRANSFORM aggfunction
selectstatement
PIVOT pivotfield [IN (value1[, value2[, ...]])]

The TRANSFORM statement has these parts:

Part	Description

aggfunction	An SQL aggregate function that operates on the selected data.

selectstatement	A SELECT statement.

pivotfield	The field or expression you want to use to create column headings in the query's result set.

value1, value2	Fixed values used to create column headings.

Remarks

When you summarize data using a crosstab query, you select values from specified fields or expressions as column headings so you can view data in a more compact format than with a select query.

TRANSFORM is optional but when included is the first statement in an SQL string.  It precedes 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 values returned in pivotfield are used as column headings in the query's result set.  For example, pivoting the sales figures on the month of the sale in a crosstab query would create 12 columns.  You can restrict pivotfield to create headings from fixed values (value1, value2 ) listed in the optional IN clause.  You can also include fixed values for which no data exists to create additional columns.


TRANSFORM Statement Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
PARAMETERS [Sales for which year?] LONG;  TRANSFORM Sum(OrderDetails.Quantity * (OrderDetails. UnitPrice - (OrderDetails.Discount / 100) * OrderDetails. UnitPrice)) AS Sales  SELECT ProductName  FROM Orders INNER JOIN (Products INNER JOIN OrderDetails  ON Products.ProductID = OrderDetails.ProductID) ON Orders.OrderID = OrderDetails.OrderID  WHERE DatePart("yyyy", OrderDate) = [Sales for which year?]  GROUP BY ProductName  ORDER BY ProductName  PIVOT DatePart("m", OrderDate);	Creates a crosstab query that shows product sales by month for a user-specified year.  The months are returned from left to right (pivoted) as columns, and the product names are returned from top to bottom as rows.
PARAMETERS [Sales for which year?] LONG;  TRANSFORM Sum(OrderDetails.Quantity * (OrderDetails. UnitPrice - (OrderDetails.Discount / 100) * OrderDetails. UnitPrice)) AS Sales  SELECT CompanyName  FROM Orders INNER JOIN  ((Suppliers INNER JOIN Products ON Suppliers.SupplierID = Products.SupplierID)  INNER JOIN OrderDetails ON  Products.ProductID = OrderDetails.ProductID)  ON Orders.OrderID = OrderDetails.OrderID  WHERE DatePart("yyyy", OrderDate) = [Sales for which year?]  GROUP BY CompanyName  ORDER BY CompanyName  PIVOT "Qtr " & DatePart("q", OrderDate)  In ('Qtr 1', 'Qtr 2', 'Qtr 3', 'Qtr 4');	Creates a crosstab query that returns product sales by quarter for each supplier for a user-specified year.  The quarters are returned from left to right (pivoted) as columns, and the supplier names are returned from top to bottom as rows.


See Also

Execute Method

FROM Clause (SQL)

INNER JOIN Operation (SQL)

ORDER BY Clause (SQL)


UPDATE Statement (SQL)

See Also	Example

Creates an update query that changes values in fields in a specified table based on specified criteria.

Syntax

UPDATE table
SET newvalue
WHERE criteria;

The UPDATE statement has these parts:

Part	Description

table	The name of the table whose data you want to modify.

newvalue	An expression that determines the value to be inserted into a particular field in the updated records.

criteria	An expression that determines which records will be updated.  Only records that satisfy the expression are updated.

Remarks

UPDATE is especially useful when you want to change many records or when the records that you want to change are in multiple tables.

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 for shippers in the United Kingdom:

UPDATE Orders
SET [Order Amount] = [Order Amount] * 1.1,
Freight = Freight * 1.03
WHERE ShipCountry = 'UK';

UPDATE doesn't generate a result set.  If you want to know which records will be changed, first examine the results of a select query that uses the same criteria, and then run the update query.


See Also

Execute Method

Retrieving Data Using SQL


UPDATE Statement Example

The SQL statements shown below should be used with the Execute method.

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 UnitPrice = UnitPrice * 1.1  WHERE SupplierID = 8  AND Discontinued = No;	Increases the UnitPrice for all nondiscontinued products from supplier 8 by 10 percent.
UPDATE Suppliers INNER JOIN Products  ON Suppliers.SupplierID = Products.SupplierID  SET UnitPrice = UnitPrice * .95  WHERE CompanyName = 'Tokyo Traders'  AND Discontinued = No;	Reduces the UnitPrice for all nondiscontinued products supplied by Tokyo Traders by 5 percent.  The Products and Suppliers tables have a many-to-one relationship.


WITH OWNERACCESS OPTION Declaration (SQL)

See Also

In a multiuser environment with a secure workgroup, use the WITH OWNERACCESS OPTION with a query to give the user who runs the query permission to use the tables in the query with the same permissions assigned to the query's owner, rather than the user's own.

Syntax

sqlstatement
WITH OWNERACCESS OPTION

Remarks

The WITH OWNERACCESS OPTION declaration is optional.

The following example enables the user to return salary information, even if the user doesn't otherwise have permission to view the Payroll table, provided the query is created by someone who has that permission:

SELECT LastName,
FirstName, Salary
FROM Employees
ORDER BY LastName
WITH OWNERACCESS OPTION;

If a user is otherwise prevented from creating or adding to a table, you can use WITH OWNERACCESS OPTION to enable the user to run a make-table or append query.

If you want to enforce workgroup security settings and users' permissions, don't include the WITH OWNERACCESS OPTION declaration.

This option requires you to have access to the SYSTEM.MDW file associated with the database.  It's really useful only in secured multiuser implementations.


See Also

Retrieving Data Using SQL

SELECT Statement (SQL)


Equivalent ANSI SQL Data Types

See Also

The following table lists ANSI SQL data types and the equivalent Microsoft Jet database engine SQL data types and their valid synonyms.

ANSI SQL  data type	Jet engine  SQL data type	Synonym
BIT, BIT VARYING	BINARY (See Notes)	VARBINARY
Not supported	BIT (See Notes)	BOOLEAN, LOGICAL, LOGICAL1, YESNO
Not supported	BYTE	INTEGER1
Not supported	COUNTER	AUTOINCREMENT
Not supported	CURRENCY	MONEY
DATE, TIME, TIMESTAMP	DATETIME	DATE, TIME, TIMESTAMP
DECIMAL	Not supported
REAL	SINGLE	FLOAT4, IEEESINGLE, REAL
DOUBLE PRECISION, FLOAT	DOUBLE	FLOAT, FLOAT8, IEEEDOUBLE, NUMBER, NUMERIC
SMALLINT	SHORT	INTEGER2, SMALLINT
INTEGER	LONG	INT, INTEGER, INTEGER4
INTERVAL	Not supported
Not supported	LONGBINARY	GENERAL, OLEOBJECT
Not supported	LONGTEXT	LONGCHAR, MEMO, NOTE
CHARACTER, CHARACTER VARYING	TEXT	ALPHANUMERIC, CHAR, CHARACTER, STRING, VARCHAR
Not supported	VALUE (See Notes)
Notes

The ANSI SQL BIT data type doesn't correspond to the Jet engine SQL BIT data type, but it corresponds to the BINARY data type instead.  There is no ANSI SQL equivalent for the Jet engine SQL BIT data type.

The BINARY data type is recognized only for use in queries on attached tables from other database products that support the BINARY data type.

The VALUE reserved word doesn't represent a data type defined by the Jet engine.  However, in Microsoft Access or SQL queries, VALUE can be considered a valid synonym for the Visual Basic Variant data type.


See Also

Comparison of Data Types

Microsoft Jet Database Engine SQL Data Types


Comparison of Data Types

See Also

The Microsoft Jet database engine recognizes several overlapping sets of data types; which data type you use depends on whether or not you're writing code in Visual Basic or in one of the Microsoft Access development contexts.  In Microsoft Access, there are four different contexts, each with its own set of data types [image] a table's Design view, the Query Parameters dialog box, Access Basic, and a query's SQL view.  See online Help in Microsoft Access for more information on these contexts.

The following table compares the four sets of data types that correspond to each context.  The first column lists the Type property settings available in a table's Design view and the five FieldSize property settings for the Number data type.  The second column lists the data types for designing parameter queries that are available in the Query Parameters dialog box.  The third column lists the Visual Basic data types.  The fourth column lists the Microsoft Access SQL data types defined by the Jet engine along with their valid synonyms.

Table fields	Query  parameters	Visual  Basic	Microsoft Access SQL and synonyms
Not supported	Binary	Not supported	BINARY (See Notes) VARBINARY
Yes/No	Yes/No	Boolean	BIT BOOLEAN, LOGICAL, LOGICAL1, YESNO
Number; Size = Byte	Byte	Byte	BYTE INTEGER1
Counter	Not supported	Long	COUNTER AUTOINCREMENT
Currency	Currency	Currency	CURRENCY MONEY
Date/Time	Date/Time	Variant (See Notes)	DATETIME DATE, TIME, TIMESTAMP
Number; Size = Single	Single	Single	SINGLE, FLOAT4, IEEESINGLE, REAL
Number; Size = Double	Double	Double	DOUBLE FLOAT, FLOAT8, IEEEDOUBLE, NUMBER, NUMERIC
Number; Size = Integer	Integer (See Notes)	Integer (See Notes)	SHORT, INTEGER2, SMALLINT
Number; Size = Long Integer	Long Integer	Long	LONG (See Notes) INT, INTEGER, INTEGER4
OLE Object	OLE Object	String	LONGBINARY GENERAL, OLEOBJECT
Memo	Memo	String	LONGTEXT LONGCHAR, MEMO, NOTE
Text	Text	String	TEXT ALPHANUMERIC, CHAR, CHARACTER, STRING, VARCHAR
Not supported	Value	Variant	VALUE (See Notes)
Notes

The Jet engine itself doesn't use the BINARY data type.  It's recognized only for use in queries on attached tables from other database products that support the BINARY data type.

If you want to declare a Visual Basic variable that contains date/time information, declare it as a Variant.  If you create a Date/Time table field in SQL view or in a table's Design view using Microsoft Access, check the field's Type property in Visual Basic; the returned integer constant corresponds to the constant dbDate (defined by the Jet engine) instead of the Variant date constant vbDate.  The variable types represented by these two constants are fully compatible, however, and no type mismatch error will occur if a Variant variable contains data from a Date/Time field in a Jet engine table or query.

The Integer data type in Jet engine SQL doesn't correspond to the Integer data type for table fields, query parameters, or Visual Basic.  Instead, in Jet engine SQL, Integer corresponds to a Long Integer for table fields and query parameters and to a Long data type in Visual Basic.

The VALUE reserved word doesn't represent a data type defined by the Jet database engine.  However, in Microsoft Access or SQL queries, VALUE can be considered a valid synonym for the Visual Basic Variant data type.


 See Also

Equivalent ANSI SQL Data Types

Microsoft Jet Database Engine SQL Data Types

Microsoft Jet Database Engine SQL Reserved Words

Type Property

Visual Basic Data Types


Microsoft Jet Database Engine SQL Reserved Words

The following list includes all words reserved by the Microsoft Jet database engine for use in SQL statements.  The words in the list that aren't in all uppercase letters are also reserved by other applications, including Microsoft Visual Basic.  Consequently, the individual Help topics for these words provide general descriptions that don't focus on SQL usage.

Note   Words followed by an asterisk (*) are reserved by the Jet engine but currently have no meaning in the context of a Jet engine SQL statement (for example, Level and TableID).

A-D

ADD ALL  Alphanumeric [image] See TEXT ALTER  And  ANY  AS  ASC AUTOINCREMENT [image] See COUNTER Avg Between BINARY  BIT  BOOLEAN [image] See BIT BY BYTE  CHAR, CHARACTER [image] See TEXT	COLUMN CONSTRAINT  Count COUNTER CREATE  CURRENCY  DATABASE DATE [image] See DATETIME DATETIME  DELETE DESC DISALLOW DISTINCT  DISTINCTROW  DOUBLE   DROP
E-K

Eqv  EXISTS FLOAT, FLOAT8 [image] See DOUBLE FLOAT4 [image] See SINGLE FOREIGN FROM  GENERAL [image] See LONGBINARY GROUP  HAVING  IEEEDOUBLE [image] See DOUBLE IEEESINGLE [image] See SINGLE IGNORE	Imp  IN  In NDEX  INNER  INSERT INT, INTEGER, INTEGER4 [image] See LONG INTEGER1 [image] See BYTE INTEGER2 [image] See SHORT INTO Is JOIN KEY
L-R

LEFT Level* Like LOGICAL, LOGICAL1 [image] See BIT LONG  LONGBINARY  LONGTEXT  Max  MEMO [image] See LONGTEXT Min  Mod  MONEY [image] See CURRENCY Not NULL  NUMBER [image] See DOUBLE NUMERIC [image] See DOUBLE	OLEOBJECT [image] See LONGBINARY ON OPTION Or  ORDER  Outer* OWNERACCESS  PARAMETERS  PERCENT  PIVOT  PRIMARY  PROCEDURE  REAL [image] See SINGLE REFERENCES  RIGHT
S-Z

SELECT  SET  SHORT  SINGLE  SMALLINT [image] See SHORT SOME  StDev StDevP  STRING [image] See TEXT Sum TABLE TableID* TEXT  TIME [image] See DATETIME TIMESTAMP [image] See DATETIME	TOP  TRANSFORM  UNION  UNIQUE  UPDATE  VALUE  VALUES  Var  VARBINARY [image] See BINARY VARCHAR [image] See TEXT VarP  WHERE  WITH  Xor YESNO [image] See BIT


Comparison of Microsoft Jet Database Engine SQL and ANSI SQL

See Also

Microsoft Jet database engine SQL is generally ANSI-89 Level 1 compliant.  However, certain ANSI SQL features aren't implemented in Jet engine SQL.  Conversely, Jet engine SQL includes reserved words and features not supported in ANSI SQL.

Major Differences

Jet engine SQL and ANSI SQL each have different reserved words and data types.  For more information, see Microsoft Jet Database Engine SQL Reserved Words and Equivalent ANSI SQL Data Types.

Different rules apply to the Between...And construct, which has the following syntax:

expression1 [NOT] BETWEEN expression2 AND expression3

In Jet engine SQL, expression2 can be greater than expression3; in ANSI SQL, expression2 must be equal to or less than expression3.

Different wildcard characters are used with the Like predicate.

Matching character	Jet engine SQL	ANSI SQL
Any single character	?	_ (underscore)
Zero or more characters	*	%
Jet engine SQL is generally less restrictive.  For example, it permits grouping and ordering on expressions.

Jet engine SQL supports more powerful expressions.  For example, you can include any Visual Basic in a Jet engine SQL statement.

Enhanced Features of Jet Engine SQL

The TRANSFORM statement, which provides support for crosstab queries

Additional aggregate functions, such as StDev and VarP

The PARAMETERS declaration for defining parameter queries

ANSI SQL Features Not Supported in Jet Engine SQL

Security statements, such as COMMIT, GRANT, and LOCK; instead, you can use Visual Basic.

DISTINCT aggregate function references.  For example, Jet engine SQL doesn't allow SUM(DISTINCT columnname).

The LIMIT TO nn ROWS clause used to limit the number of rows returned by a query. Only the WHERE clause can be used to limit the scope of a query.


 See Also

Equivalent ANSI SQL Data Types

Microsoft Jet Database Engine SQL Reserved Words


ALTER TABLE Statement (SQL)

See Also	Example

Modifies the design of a table after it has been created with the CREATE TABLE statement.

Note   The Microsoft Jet database engine doesn't support the use of ALTER TABLE, or any of the data definition language (DDL) statements, with non-Jet databases.  Use the data access object Create methods instead.

Syntax

ALTER TABLE table {ADD {COLUMN field type[(size)] [CONSTRAINT index] I
CONSTRAINT multifieldindex} |
DROP {COLUMN field I CONSTRAINT indexname} }

The ALTER TABLE statement has these parts:

Part	Description

table	The name of the table to be altered.

field	The name of the field to be added to or deleted from table.

type	The data type of field.

size	The field size in characters (Text data type and Binarydata type fields only).

index	The index for field.  See the CONSTRAINT clause topic for more information on how to construct this index.

multifieldindex	The definition of a multiple-field index to be added to table.  See the CONSTRAINT clause topic for more information on how to construct this clause.

indexname	The name of the multiple-field index to be removed.

Remarks

Using the ALTER TABLE statement, you can alter an existing table in several ways.  You can:

Use ADD COLUMN to add a new field to the table.  You specify the field name, data type, and (for Text and Binary fields) an optional size.  For example, the following statement adds a 25-character Text field called Notes to the Employees table:

ALTER TABLE Employees ADD COLUMN Notes TEXT(25)

You can also define an index on that field.  For more information on single-field indexes, see the CONSTRAINT clause topic.

Use the ADD constraint to add a multiple-field index.  For more information on multiple-field indexes, see the CONSTRAINT clause topic.

Use DROP COLUMN to delete a field.  You specify only the name of the field.

Use the DROP constraint to delete a multiple-field index.  You specify only the index name following the CONSTRAINT reserved word.

Notes

You can't add or delete more than one field or index at a time.

You can use the CREATE INDEX statement to add a single- or multiple-field index to a table, and you can use ALTER TABLE or the DROP statement to delete an index created with ALTER TABLE or CREATE INDEX.


 See Also

CONSTRAINT Clause (SQL)

CREATE INDEX Statement (SQL)

CREATE TABLE Statement (SQL)

CreateTableDef Method

DROP Statement (SQL)


ALTER TABLE Statement Example

The SQL statements shown below can be used on tables created with the CREATE TABLE statement.

SQL statement	Description
ALTER TABLE Employees  ADD COLUMN Salary CURRENCY;	Adds a Salary field with a data type of Currency to the Employees table.
ALTER TABLE Employees  DROP COLUMN Salary;	Removes the Salary field from the Employees table.
ALTER TABLE Orders  ADD CONSTRAINT OrdersRelationship  FOREIGN KEY (EmployeeID)  REFERENCES Employees (EmployeeID);	Adds a foreign key to the Orders table.  The foreign key is based on the EmployeeID field and refers to the EmployeeID field of the Employees table.  In this example, you don't have to list the EmployeeID field after the Employees table in the REFERENCES clause because EmployeeID is the primary key of the Employees table.
ALTER TABLE Orders  DROP CONSTRAINT OrdersRelationship;	Removes the foreign key from the Orders table.


CONSTRAINT Clause (SQL)

See Also	Example

A constraint is similar to an index, although it can also be used to establish a relationship with another table.

You use the CONSTRAINT clause in ALTER TABLE and CREATE TABLE statements to create or delete constraints.  There are two types of CONSTRAINT clauses: one for creating a constraint on a single field and one for creating a constraint on more than one field.

Note   The Microsoft Jet database engine doesn't support the use of CONSTRAINT, or any of the data definition language (DDL) statements, with non-Jet databases.  Use the data access object Create methods instead.

Syntax

Single-field index:

CONSTRAINT name {PRIMARY KEY |
UNIQUE |
REFERENCES foreigntable [(foreignfield1, foreignfield2)]}

Multiple-field index:

CONSTRAINT name
{PRIMARY KEY (primary1[, primary2 [, ...]]) |
UNIQUE (unique1[, unique2 [, ...]]) |
FOREIGN KEY (ref1[, ref2 [, ...]]) REFERENCES foreigntable [(foreignfield1 [, foreignfield2 [, ...]])]}

The CONSTRAINT clause has these parts:

Part	Description
name	The name of the constraint  to be created.
primary1, primary2	The name of the field or fields to be designated the primary key.
unique1, unique2	The name of the field or fields to be designated as a unique key.
ref1, ref2	The name of a foreign key field or fields that refer to fields in another table.
foreigntable	The name of the foreign table containing the field or fields specified by foreignfield.
foreignfield1, foreignfield2	The name of the field or fields in foreigntable specified by ref1, ref2.  You can omit this clause if the referenced field is the primary key of foreigntable.
Remarks

You use the syntax for a single-field index in the field-definition clause of an ALTER TABLE or CREATE TABLE statement immediately following the specification of the field's data type.

You use the syntax for a multiple-field index whenever you use the reserved word CONSTRAINT outside a field-definition clause in an ALTER TABLE or CREATE TABLE statement.

Using CONSTRAINT, you can designate a field as one of the following types of constraints:

You can use the UNIQUE reserved word to designate a field as a unique key.  This means that no two records in the table can have the same value in this field.  You can constrain any field or list of fields as unique.  If a multiple-field index is designated as a unique key, the combined values of all fields in the index must be unique, even if two or more records have the same value in just one of the fields.

You can use the PRIMARY KEY reserved words to designate one field or set of fields in a table as a primary key.  All values in the primary key must be unique and not Null, and there can be only one primary key for a table.

Note   Don't set a PRIMARY KEY constraint on a table that already has a primary key; if you do, an error occurs.

You can use the FOREIGN KEY reserved words to designate a field as a foreign key.  If the foreign table's primary key consists of more than one field, you must use a multiple-field index definition, listing all of the referencing fields, the name of the foreign table, and the names of the referenced fields in the foreign table in the same order that the referencing fields are listed.  If the referenced field or fields are the foreign table's primary key, you don't have to specify the referenced fields [image] by default, the Jet engine behaves as if the foreign table's primary key is the referenced fields.


See Also

ALTER TABLE Statement (SQL)

CREATE INDEX Statement (SQL)

CREATE TABLE Statement (SQL)

DROP Statement (SQL)


CREATE INDEX Statement (SQL)

See Also	Example

Creates a new index on an existing table.

Note   The Microsoft Jet database engine doesn't support the use of CREATE INDEX, or any of the data definition language (DDL) statements, with non-Jet databases.  Use the data access object Create methods instead.

Syntax

CREATE [ UNIQUE ] INDEX index
ON table (field [ASC|DESC][, field [ASC|DESC], ...])
[WITH { PRIMARY | DISALLOW NULL | IGNORE NULL }]

The CREATE INDEX statement has these parts:

Part	Description

index	The name of the index to be created.

table	The name of the existing table the index will be created on.

field	The name of the field or fields to be indexed.  To create a single-field index, list the field name in parentheses following the table name.  To create a multiple-field index, list the name of each field to be included in the index.  To create descending indexes, use the DESC reserved word; otherwise, indexes are assumed to be ascending.

Remarks

To prohibit duplicate values in the indexed field or fields of different records, use the UNIQUE reserved word.

In the optional WITH clause, you can enforce data validation rules.  You can:

Prohibit Null entries in the indexed field or fields of new records by using the DISALLOW NULL option.

Prevent records with Null values in the indexed field or fields from being included in the index by using the IGNORE NULL option.

Designate the indexed field or fields as the primary key by using the PRIMARY reserved word.  This implies that the key is unique, so you can omit the UNIQUE reserved word.

You can use CREATE INDEX to create a pseudo index on an attached table in an ODBC data source such as SQL Server that does not already have an index.  You don't need permission or access to the remote server to create a pseudo index, and the remote database is unaware of and unaffected by the pseudo index.  You use the same syntax for attached and native tables. This can be especially useful to create an index on a table that would ordinarily be read-only due to lack of an index.

You can also use the ALTER TABLE statement to add a single- or multiple-field index to a table, and you can use the ALTER TABLE statement or the DROP statement to remove an index created with ALTER TABLE or CREATE INDEX.

Note   Don't use the PRIMARY reserved word when you create a new index on a table that already has a primary key; if you do, an error occurs.


See Also

ALTER TABLE Statement (SQL)

CONSTRAINT Clause (SQL)

CREATE TABLE Statement (SQL)

DROP Statement (SQL)

Execute Method


CREATE INDEX Statement Example

Generally, you use the CREATE INDEX statement, as shown in these examples, with the Execute method.

SQL statement	Description
CREATE INDEX NewIndex  ON Employees (Home Phone, Extension);	Creates an index consisting of the fields Home Phone and Extension in the Employees table.
CREATE UNIQUE INDEX MyIndex  ON Employees (SSN)  WITH DISALLOW NULL;	Creates an index on the Employees table using the Social Security Number field.  No two records can have the same data in the SSN field, and no Null values are allowed.
CREATE UNIQUE INDEX MailID  ON MailList (Client No.)	Creates an index on an attached table.  The table's remote database is unaware of and unaffected by the new index.  This method does not work for all types of attached tables, more specifically, for any type using ISAMs.


CREATE TABLE Statement (SQL)

See Also	Example

Creates a new table.

Note   The Microsoft Jet database engine doesn't support the use of CREATE TABLE, or any of the data definition language (DDL) statements, with non-Jet databases.  Use the data access object Create methods instead.

Syntax

CREATE TABLE table (field1 type [(size)] [index1] [, field2 type [(size)] [index2] [, ...]] [, multifieldindex [, ...]])

The CREATE TABLE statement has these parts:

Part	Description

table	The name of the table to be created.

field1, field2	The name of field or fields to be created in the new table.  You must create at least one field.

type	The data type of field in the new table.

size	The field size in characters (Text and Binary fields only).

index1, index2	A CONSTRAINT clause defining a single-field index.  See the CONSTRAINT clause topic for more information on how to create this index.

multifieldindex	A CONSTRAINT clause defining a multiple-field index.  See the CONSTRAINT clause topic for more information on how to create this index.

Remarks

Generally, you use the CREATE TABLE statement with the Execute method.  You can also use the CREATE INDEX statement to create indexes on existing tables.


See Also

ALTER TABLE Statement (SQL)

CONSTRAINT Clause (SQL)

CREATE INDEX Statement (SQL)

CreateTableDef Method

DROP Statement (SQL)

Execute Method


CREATE TABLE Statement, CONSTRAINT Clause Example

Generally, you use the CREATE TABLE statement, as shown in the examples below, with the Execute method.

SQL statement	Description
CREATE TABLE [This Table]  (FirstName TEXT, LastName TEXT);	Creates a new table called This Table with two Text fields.
CREATE TABLE MyTable (FirstName TEXT, LastName TEXT, [Date of Birth] DATETIME,  CONSTRAINT MyTableConstraint UNIQUE (FirstName, LastName, [Date of Birth]));	Creates a new table called MyTable with two Text fields, a Date/Time field, and a unique index made up of all three fields.
CREATE TABLE NewTable  (FirstName TEXT, LastName TEXT,  SSN INTEGER  CONSTRAINT MyFieldConstraint PRIMARY  KEY)	Creates a new table with two Text fields and an Integer field.  The SSN field is the primary key.


DROP Statement (SQL)

See Also	Example

Deletes an existing table from a database or deletes an existing index from a table.

Note   The Microsoft Jet database engine doesn't support the use of DROP, or any of the data definition language (DDL) statements, with non-Jet databases.  Use the data access object Create methods instead.

Syntax

DROP {TABLE table | INDEX index ON table}

The DROP statement has these parts:

Part	Description

table	The name of the table to be deleted or the table from which an index is to be deleted.

index	The name of the index to be deleted from table.

Remarks

You must close the table before you can delete it or remove an index from it.

You can also use ALTER TABLE to delete an index from a table.

You can use CREATE TABLE to create a table and CREATE INDEX or ALTER TABLE to create an index.  To modify a table, use ALTER TABLE.

Note   Generally, you use the DROP statement with the Execute method.


See Also

ALTER TABLE Statement (SQL)

CONSTRAINT Clause (SQL)

CREATE INDEX Statement (SQL)

CREATE TABLE Statement (SQL)

Execute Method


DROP Statement Example

Generally, you use the DROP statement, as shown in the examples below, with the Execute method.

SQL statement	Description
DROP INDEX MyIndex ON Employees;	Deletes MyIndex from the Employees table.
DROP TABLE [This Table];	Deletes This Table from the database.


UNION Operation (SQL)

See Also	Example

You use the UNION operation to create a union query, combining the results of two or more independent queries or tables.

Syntax

[TABLE] query1 UNION [ALL] [TABLE] query2 [UNION [ALL] [TABLE] queryn [ ... ]]

The UNION operation has these parts:

Part	Description

query1, query2, queryn	A SELECT statement, the name of a stored query, or the name of a stored table preceded by the TABLE keyword.

Remarks

You can merge the results of two or more queries, tables, and SELECT statements,  in any combination, in a single UNION operation.  The following example merges an existing table named New Accounts and a SELECT statement:

TABLE [New Accounts] UNION ALL
SELECT *
FROM Customers
WHERE [Order Amount] > 1000;

By default, no duplicate records are returned when you use a UNION operation; however, you can include the ALL predicate to ensure that all records are returned.  This also makes the query run faster.

All queries in a UNION operation must request the same number of fields; however, the fields don't have to be of the same size or data type.

Notes

You can use a GROUP BY and/or HAVING clause in each query argument to group the returned data.

You can use an ORDER BY clause at the end of the last query argument to display the returned data in a specified order.


See Also

ALL, DISTINCT, DISTINCTROW, TOP Predicates (SQL)

GROUP BY Clause (SQL)

HAVING Clause (SQL)

INNER JOIN Operation (SQL)

LEFT JOIN, RIGHT JOIN Operations (SQL)

ORDER BY Clause (SQL)

SELECT Statement (SQL)

SQL Subqueries

WHERE Clause (SQL)


UNION Operation Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT CompanyName, City  FROM Suppliers  WHERE Country = "Brazil"  UNION SELECT CompanyName, City  FROM Customers  WHERE Country = "Brazil";	Retrieves the names and cities of all suppliers and customers in Brazil.
SELECT CompanyName, City  FROM Suppliers  WHERE Country = "Brazil"  UNION SELECT CompanyName, City  FROM Customers  WHERE Country = "Brazil";  ORDER BY City;	Retrieves the names and cities of all suppliers and customers located in Brazil, arranged by city name.
SELECT CompanyName, City  FROM Suppliers  WHERE Country = "Brazil"  UNION SELECT CompanyName, City  FROM Customers  WHERE Country = "Brazil"  UNION SELECT LastName, City  FROM Employees  WHERE Region = "South America"	Retrieves the names and cities of all suppliers and customers in Brazil and the last names and cities of all employees in South America.
TABLE Customers  UNION TABLE Suppliers	Retrieves the names and IDs of all suppliers and customers.


SQL Subqueries

See Also	Example

A subquery is a SELECT statement nested inside a SELECT, SELECT...INTO, INSERT...INTO, DELETE, or UPDATE statement or inside another subquery.

Syntax

You can use three forms of syntax to create a subquery:

comparison [ANY | ALL | SOME] (sqlstatement)

expression [NOT] IN (sqlstatement)

 [NOT] EXISTS (sqlstatement)

A subquery has these parts:

Part	Description

comparison	An expression and a comparison operator that compares the expression with the results of the subquery.

expression	An expression for which the result set of the subquery is searched.

sqlstatement	A SELECT statement, following the same format and rules as any other SELECT statement.  It must be enclosed in parentheses.

Remarks

You can use a subquery instead of an expression in the field list of a SELECT statement or in a WHERE or HAVING clause.  In a subquery, you use a SELECT statement to provide a set of one or more specific values to evaluate in the WHERE or HAVING clause expression.

Use the ANY or SOME predicate, which are synonymous, to retrieve records in the main query that satisfy the comparison with any records retrieved in the subquery.  The following example returns all products whose unit price is greater than that of any product sold at a discount of 25 percent or more:

SELECT * FROM Products
WHERE UnitPrice > ANY
(SELECT UnitPrice FROM OrderDetails
WHERE [Discount] >= .25);

Use the ALL predicate to retrieve only those records in the main query that satisfy the comparison with all records retrieved in the subquery.  If you changed ANY to ALL in the above example, the query would return only those products whose unit price is greater than that of all products sold at a discount of 25 percent or more.  This is much more restrictive.

Use the IN predicate to retrieve only those records in the main query for which some record in the subquery contains an equal value.  The following example returns all products sold at a discount of 25 percent or more:

SELECT * FROM Products
WHERE ProductID IN
(SELECT ProductID FROM OrderDetails
WHERE [Discount] >= .25);

Conversely, you can use NOT IN to retrieve only those records in the main query for which no record in the subquery contains an equal value.

Use the EXISTS predicate (with the optional NOT reserved word) in true/false comparisons to determine whether the subquery returns any records.

You can also use table name aliases in a subquery to refer to tables listed in a FROM clause outside the subquery.  The following example returns the names of employees whose salaries are equal to or greater than the average salary of all employees with the same job title.  The Employees table is given the alias "T1"::

SELECT LastName,
FirstName, Title, Salary
FROM Employees AS T1
WHERE Salary >=
(SELECT Avg(Salary)
FROM Employees
WHERE T1.Title = Employees.Title) Order by Title;

In the preceding example, the AS reserved word is optional.


See Also

Comparison Operators

INNER JOIN Operation (SQL)

LEFT JOIN, RIGHT JOIN Operations (SQL)

SELECT Statement (SQL)

SELECT...INTO Statement (SQL)

UNION Operation (SQL)


SQL Subqueries Example

The SQL statements shown below must be used as the SQL property of a QueryDef object or in an SQL expression with the OpenRecordset method.

SQL statement	Description
SELECT LastName, FirstName, Title, Salary  FROM Employees  WHERE Title LIKE "*Sales Rep*" AND Salary > ALL  (SELECT Salary FROM Employees  WHERE (Title LIKE "*Manager*") OR (Title LIKE "*Director*"));	Lists the name, title, and salary of every sales representative whose salary is higher than that of all managers and directors.
SELECT DISTINCTROW ProductName, UnitPrice  FROM Products WHERE UnitPrice =  (SELECT UnitPrice FROM [Products]  WHERE ProductName = "Aniseed Syrup");	Lists the name and unit price of every product whose unit price is the same as that of Aniseed Syrup.
SELECT DISTINCTROW [Contact Name], CompanyName, [Contact Title], Phone  FROM Customers WHERE CustomerID IN  (SELECT DISTINCTROW CustomerID  FROM Orders WHERE OrderDate BETWEEN #04/1/94# AND #07/1/94#);	Lists the company and contact of every customer who placed an order in the second quarter of 1994.
SELECT LastName, FirstName, Title, Salary  FROM Employees T1  WHERE Salary >=  (SELECT AVG(Salary)  FROM Employees  WHERE Employees.Title = T1.Title)  ORDER BY Title;	Lists employees whose salary is higher than the average salary for all employees.
SELECT FirstName, LastName  FROM Employees AS E  WHERE EXISTS  (SELECT *  FROM Orders AS O  WHERE O.EmployeeID = E.EmployeeID);	Selects the name of every employee who has booked at least one order.  This could also be done with an INNER JOIN.


Microsoft Jet Database Engine SQL Data Types

See Also

The Microsoft Jet engine SQL data types consist of 13 primary data types defined by the Microsoft Jet database engine and several valid synonyms recognized for these data types.

The following table lists the primary data types.  The synonyms are identified in the Comparison of Data Types and Jet Database Engine SQL Reserved Words topics.

Data type	Storage size	Description
BINARY	1 byte	For queries on attached tables from database products that define a Binary data type.
BIT	1 byte	Yes and No values and fields that contain only one of two values.
BYTE	1 byte	An integer value between 0 and 255.
COUNTER	4 bytes	A number automatically incremented by the Jet engine whenever a new record is added to a table.  In the Jet engine, the data type for this value is a Long.
CURRENCY	8 bytes	A scaled integer between -922,337,203,685,477.5808 and 922,337,203,685,477.5807.
DATETIME (See DOUBLE)	8 bytes	A date or time value between the years 100 and 9999.
SINGLE	4 bytes	A single-precision floating-point value with a range of -3.402823E38 to -1.401298E-45 for negative values, 1.401298E-45 to 3.402823E38 for positive values, and 0.
DOUBLE	8 bytes	A double-precision floating-point value with a range of -1.79769313486232E308 to -4.94065645841247E-324 for negative values, 4.94065645841247E-324 to 1.79769313486232E308 for positive values, and 0.
SHORT	2 bytes	A short integer between -32,768 and 32,767.
LONG	4 bytes	A long integer between -2,147,483,648 and 2,147,483,647.
LONGTEXT	1 byte per character	Zero to a maximum of 1.2 gigabytes.
LONGBINARY	As required	Zero to a maximum of approximately 1 gigabyte.  Used for OLE objects.
TEXT	1 byte per character	Zero to 255 characters.
Note   You can also use the VALUE reserved word in SQL statements.  Although it doesn't represent a data type defined by the Jet database engine, VALUE can be considered a valid synonym for the Microsoft Visual Basic Variant data type.


 See Also

Comparison of Data Types

Type Property

Equivalent ANSI SQL Data Types

Size Property

Microsoft Jet Database Engine SQL Reserved Words

Visual Basic Data Types


SQL Aggregate Functions (SQL Only)

Using the SQL aggregate functions, you can determine various statistics on sets of values.  You can use these functions in a query expression, but not in Microsoft Visual Basic code outside of an SQL query string.  You can also use aggregate expressions in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

Avg Function

Count Function

Min, Max Functions

StDev, StDevP Functions

Sum Function

Var, VarP Functions


Avg Function (SQL)

See Also	Example

Calculates the arithmetic mean of a set of values contained in a specified field on a query.

Syntax

Avg(expr)

The expr placeholder represents a 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, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate  functions).

Remarks

The average calculated by Avg is the arithmetic mean (the sum of the values divided by the number of values).  You could use Avg, for example, to calculate average freight cost.

The Avg function doesn't include any Null fields in the calculation.

You can use Avg in a query expression and in the SQL property of a QueryDef object or when creating a Recordset based on an SQL query.


See Also

SQL Aggregate Functions


Avg Function Example

This example uses an Orders table to calculate the average freight charges for orders with freight charges over $100.

SELECT Avg([Freight])
AS [Average Freight]
FROM Orders WHERE [Freight] > 100;


Count Function (SQL)

See Also	Example

Calculates the number of records returned by a query.

Syntax

Count(expr)

The expr placeholder represents a 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 function (which can be either intrinsic or user-defined but not other SQL aggregate functions).  You can count any kind of data, including text.

Remarks

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 asterisk (*) wildcard character.  If you use an asterisk, Count calculates the total number of records, including those that contain null fields.  Count(*) is considerably faster than Count([Column Name]).  Don't enclose the asterisk in quotation marks (" ").  The following example calculates the number of records in the Orders table:

SELECT Count(*)
AS [Total Orders] 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 ShippedDate or Freight isn't Null:

SELECT
Count('ShippedDate & [Freight]')
AS [Not Null] FROM Orders;

You can use Count in a query expression.  You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


See Also

RecordCount Property

SQL Aggregate Functions

Sum Function


Count Function Example

This example uses an Orders table to calculate the number of orders shipped to the United Kingdom.  You can use this expression in the SQL property of a QueryDef object or when creating a Recordset based on an SQL query.

SELECT Count(ShipCountry)
AS [UK Orders] FROM Orders WHERE ShipCountry = 'UK';


First, Last Functions (SQL)

See Also	Example

Return a field value from the first or last record in the result set returned by a query.

Syntax

First(expr)
Last(expr)

The expr placeholder represents a 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, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

The First and Last functions can be thought of as analogous to the MoveFirst and MoveLast methods of a Recordset object.  The simply return the value of a specified field in the first or last record, respectively, of the result set returned by a query.  Since records are normally returned in no particular order (unless the query includes an ORDER BY clause), the records returned by these functions will be arbitrary.


See Also

SQL Aggregate Functions


First, Last Functions Example

This example uses an employees table to return the values from the LastName field of the first and last records returned from the table.

SELECT First(LastName), Last(LastName)

FROM Employees;

The next two examples compare using the First and Last functions with simply using the Min and Max functions to find the earliest and latest birth dates of Employees.

SELECT First(BirthDate), Last(BirthDate)

FROM Employees;

SELECT Min(BirthDate), Max(BirthDate)

FROM Employees;


Min, Max Functions (SQL)

See Also	Example

Return the minimum or maximum of a set of values contained in a specified field on a query.

Syntax

Min(expr)

Max(expr)

The expr placeholder represents a string expression identifying the field that contains the 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, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

You can use Min and Max to determine the smallest and largest values in a field based on the specified aggregation, or grouping.  For example, you could use these functions to return the lowest and highest freight cost. If there is no aggregation specified, then the entire table is used.

You can use Min and Max in a query expression and in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


See Also

SQL Aggregate Functions


Min, Max Functions Example

This example uses an Orders table to return the lowest and highest freight charges for orders shipped to the United Kingdom.  You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.

SELECT Min([Freight])
AS [Low Freight],
Max([Freight]) AS [High Freight]
FROM Orders WHERE ShipCountry = 'UK';


StDev, StDevP Functions (SQL)

See Also	Example

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)

The expr placeholder represents a 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, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

StDevP evaluates a population, and StDev evaluates a population sample.

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).

You can use StDev and StDevP in a query expression.  You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset object based on an SQL query.


See Also

Avg Function (SQL)

SQL Aggregate Functions

Sum Function (SQL)


StDev, StDevP Functions Example

This example uses an Orders table to estimate the standard deviation of the freight charges for orders shipped to the United Kingdom.

SELECT StDev([Freight])
AS [Freight Dev]
FROM Orders WHERE ShipCountry = 'UK';

SELECT StDevP([Freight])
AS [Freight DevP]
FROM Orders WHERE ShipCountry = 'UK';


Sum Function (SQL)

See Also	Example

Returns the sum of a set of values contained in a specified field on a query.

Syntax

Sum(expr)

The expr placeholder represents a 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 constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate functions).

Remarks

Sum totals the values in a field.  For example, you could use Sum to determine the total cost of freight charges.

The Sum function ignores records that contain Null fields.  The following example shows how you can calculate the sum of the products of UnitPrice and Quantity fields:

SELECT
Sum(UnitPrice * [Quantity])
AS [Total Revenue]  FROM OrderDetails;

You can use Sum in a query expression.  You can also use this expression in the SQL property of a QueryDef object or when creating a Recordset based on an SQL query.


See Also

Count Function (SQL)

SQL Aggregate Functions


Sum Function Example

This example uses an Orders table to calculate the total sales for orders shipped to the United Kingdom.

SELECT Sum(UnitPrice*[Quantity]) AS [Total UK Sales]
FROM Orders INNER JOIN OrderDetails
ON Orders.OrderID = OrderDetails.OrderID
WHERE (ShipCountry = 'UK');


Var, VarP Functions (SQL)

See Also	Example

Return estimates of the variance for a population or a population sample represented as a set of values contained in a specified field on a query.

Syntax

Var(expr)
VarP(expr)

VarP evaluates a population, and Var evaluates a population sample.

The expr placeholder represents a 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, a constant, or a function (which can be either intrinsic or user-defined but not one of the other SQL aggregate  functions).

Remarks

If the underlying query contains fewer than two records, Var and VarP return a Null (which indicates that a variance can't be calculated).

You can use Var and VarP in a query expression or in an SQL statement.


See Also

SQL Aggregate Functions


Var, VarP Functions Example

This example uses an Orders table to estimate the variance of freight costs for orders shipped to the United Kingdom.

SELECT Var([Freight])
AS [UK Freight Variance] FROM Orders
WHERE ShipCountry = 'UK';

SELECT VarP([Freight])
AS [UK Freight VarianceP]
FROM Orders WHERE ShipCountry = 'UK';


Domain Aggregate Functions (SQL)

See Also

The Domain Aggregate functions such as DAvg, DCount, DLookup, DMin, DMax, DVar, DVarP, DStdev, DStdevP, and DSum as supported in Microsoft Access are not supported in Visual Basic.  Including these functions in SQL query statements triggers a trappable error.

Note   You can use queries or subqueries instead of domain functions.


See Also

SQL Aggregate Functions


Like Operator (SQL)

See Also	Example

Used to compare a string expression to a pattern in an SQL expression.

Syntax

Expression Like "pattern"

The Like operator syntax has these parts:

Part	Description

expression	SQL expression used in a WHERE clause.

pattern	String or character string literal against which expression is compared.

Remarks

You can use the Like operator to find values in a field that match the pattern you specify.  For pattern, you can specify the complete value (for example, Like "Smith"), or you can use wildcard characters like those recognized by the operating system to find a range of values (for example, Like "Sm*").

In an expression, you can use the Like operator to compare a field value to a string expression.  For example, if you enter Like "C*" in an SQL query, the query returns all field values beginning with the letter C.  In a parameter query, you can prompt the user for a pattern to search for.

The following example returns data that begins with the letter P followed by any letter between A and F and three digits:

Like "P[A-F]###"

In Visual Basic, if expression matches pattern, result is True (-1); if there is no match, result is False (0); and if either expression or pattern is a Null, result is also a Null.


See Also

& Operator

ANSI Character Set

Arithmetic Operators

Comparison Operators

Logical Operators

Operator Precedence

Using Wildcard Characters in String Comparisons


Like Operator Example

This example returns a list of employees whose names begin with the letters A through D.

SELECT * FROM Employees WHERE LastName Like "[A-D]*"

The following table shows how you can use Like to test expressions for different patterns.

Kind of match	Pattern	Match (returns True)	No match (returns False)
Multiple characters	"a*a"	"aa", "aBa", "aBBBa"	"aBC"
	"*ab*"	"abc", "AABB", "Xab"	"aZb", "bac"
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"


Using Wildcard Characters in String Comparisons

See Also

Built-in pattern matching provides a versatile tool for making string comparisons.  The following table shows the wildcard characters you can use with the Like operator and the number of digits or strings they match.

Character(s)  in pattern	Matches in expression
?	Any single character
*	Zero or more characters
#	Any single digit (0 [image] 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 opening bracket ([ ), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only if enclosed in brackets.  The closing bracket ( ]) can't 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, using [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 can be 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 mark (!) at the beginning of charlist means that a match is made if any character except those in charlist are found in expression.  When used outside brackets, the exclamation mark matches itself.

The hyphen (-) can be used 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 (A-Z or 0-100).  [A-Z] is a valid pattern, but [Z-A] isn't.

The character sequence [ ] is ignored; it's considered to be a zero-length string ("").


See Also

Like Operator (SQL)


Between...And Operator (SQL)

See Also

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

The Between...And operator syntax has these parts:

Part	Description

expr	Expression identifying the field that contains the data you want to evaluate

value1, value2	Expressions against which you want to evaluate expr

Remarks

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.


See Also

IIf Function

IN Clause (SQL)

Retrieving Data Using SQL


Calculating Fields in SQL Functions

You can use the string expression argument in an SQL aggregate function to perform a calculation on values in a field.  For example, you could calculate a percentage (such as a surcharge or sales tax) by multiplying a field value by a fraction.

The following table provides examples of calculations on fields from Orders and OrderDetails tables in a database.

Calculation	Example
Add a number to a field	Freight + 5
Subtract a number from a field	Freight - 5
Multiply a field by a number	UnitPrice * 2
Divide a field by a number	Freigh] / 2
Add one field to another	UnitsInStock + UnitsOnOrder
Subtract one field from another	ReorderLevel - UnitsInStock
The following example calculates the average discount amount of all orders in a database.  It multiplies the values in UnitPrice and Discount fields to determine the discount amount of each order and then calculates the average.  You can use this expression in an SQL statement in Visual Basic code:

SELECT Avg(UnitPrice * Discount) AS [Average Discount] FROM OrderDetails;


In Operator

See Also	Example

Determines whether the value of an expression is equal to any of several values in a specified list.

Syntax

expr [Not] In(value1, value2,  . . .)

The In operator syntax has these parts:

Part	Description

expr	Expression identifying the field that contains the data you want to evaluate.

value1, value2	Expressions against which you want to evaluate expr.

Remarks

If expr is found in the list of values, the In operator returns True (-1); otherwise, it returns False (0).  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 which orders are shipped to a set of specified regions:

SELECT *

FROM Orders

WHERE ShipRegion In ('Avon','Glos','Som')


See Also

IN Clause (SQL)


In Operator Example

The following example uses an Orders table in a database to create a query that includes orders shipped to Avon, Gloucester, and Somerset.

SELECT * FROM Orders WHERE ShipRegion In ('Avon','Glos','Som');


AddNew Method

See Also	Example	Applies To

Creates a new record for a table-type or dynaset-type Recordset object.  The AddNew method can also be used with the outdated Dynaset and Table objects.

Syntax

object.AddNew

The object placeholder represents the name of an open table-type or dynaset-type Recordset, Dynaset object, or Table object to which you want to add a new record.

Remarks

The AddNew method creates a new record you can edit and add to the Recordset, Dynaset, or Table object named by object.  This method sets the fields to Null (the default values specified for a table-type Recordset) or default values, if any.

After you modify the new record, use the Update method to save the changes and add the record to the recordset.  No changes are made to the database until you use the Update method.

Caution   If you edit a record and then perform any operation that moves to another record without using Update, your changes are lost without warning.  In addition, if you close the object or end the procedure which declares the object or its Database object, the new record and the changes made to it are discarded without warning.

When you use AddNew and the Microsoft Jet database engine has to create a new 2K page to hold the current record, page locking is pessimistic.  If the new record fits in an existing page, page locking is optimistic.

If you haven't moved to the last record of your dynaset, records added to base tables may be included if they would be positioned beyond the current record.   If you add a record to a dynaset-type Recordset using the AddNew method on the dynaset, however, the record is visible in the Recordset and included in the underlying table where it becomes visible to any new Recordset objects.

The position of the new record depends on the type of Recordset:

In a dynaset-type Recordset or Dynaset object, records are inserted at the end of the recordset, regardless of any sorting or ordering rules that may have been in effect when the recordset was opened.

In a table-type Recordset or Table object whose Index property has been set, records are returned in their proper place in the sort order.  If the Index property hasn't been set, new records are returned at the end of the recordset.

The record that was current before you used AddNew remains current.  If you want to make the new record current, you can set the Bookmark property to the bookmark identified by the LastModified property setting.

Caution   If you use any of the DAO editing methods (AddNew, Update, Edit, or Update) within a loop that will edit more than one record, the Jet engine version 3.0 may treat the entire loop as an implicit transaction.  This means that you will not necessarily be able to guarantee that each update is immediately written to the database.  This may affect error handling, page locking, and the immediate visibility of the changes to other users.  To guarantee that changes are immediately written to the database, enclose each Edit . . . Update block within an explicit transaction.  For more information about transactions, see the BeginTrans, CommitTrans, Rollback methods.


See Also

Bookmark Property

Delete Method

Edit Method

Index Object, Indexes Collection

LastModified Property

Move Method

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Populating Recordsets

Seek Method

Update Method


AddNew Method Applies To

Dynaset Object

Recordset Object (dynaset- and table-type only)

Table Object


AppendChunk Method

See Also	Example	Applies To

Appends data from a string expression to a Memo or OLE Object Field object in the Fields collection of a Recordset object.

Syntax

recordset ! field.AppendChunk source

The AppendChunk method syntax has these parts:

Part	Description

recordset	A variable of an object data type that refers to the Recordset object containing the Fields collection.

field	The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.

source	A string expression or variable containing the data you want to append to the Field object specified by field.

Remarks

You can use the AppendChunk and GetChunk methods to access data in an OLE Object field larger than 64K (the size limit for String data types).

You can also use these methods to conserve string space when you work with Memo fields, which are limited to 1.2GB.  Certain operations (copying, for example) involve temporary strings.  If string space is limited, you may need to work with chunks of a Memo field instead of the entire field.

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

Note   The initial AppendChunk (after the first Edit method), even if the record already contains data, will simply place the data in the field as the only data.  Subsequent AppendChunk calls within a single Edit session will then add to the data.


See Also

Field Object, Fields Collection

FieldSize Method

GetChunk Method

Recordset Object, Recordsets Collection

Type Property


AppendChunk Method Applies To

Field Object


Close Method

See Also	Example	Applies To

Closes an open data access object.  The Close method can also be used with the outdated Dynaset, Snapshot, and Table objects.

Syntax

object.Close

The object placeholder represents the name of an open Database, Recordset, Workspace, Dynaset, Snapshot, or Table object.

Remarks

Closing an open object removes it from the collection to which it's appended.  Any attempt to close the default workspace is ignored.

To remove objects from collections other than the Databases, Recordsets, and Workspaces collections, use the Delete method on those collections.

Caution   Use the Update method (if there are pending edits) and the Close method on all open recordset objects before you close a database.  If you exit a procedure that declares recordset or Database objects, the database is closed, any unsaved changes are lost, all pending transactions are rolled back, and any pending edits to your data are lost.

If you try to close a Database object while any recordset objects are open, or if you try to close a Workspace object while any Database objects belonging to that specific Workspace are open, those Recordset objects will be closed and any pending updates or edits will be rolled back.

If you try to close a Workspace object while any Database objects belonging to it are open, the operation closes all Database objects belonging to that specific Workspace object which may result in unclosed Recordset objects being closed.

If the Database object is defined outside the scope of the procedure, and you exit the procedure without closing it, the Database object will remain open until explicitly closed or the module in which it is defined is out of scope.

If the recordset or DatabaseRecordset or Workspace object named by object is already closed when you use Close, a trappable error occurs.

Using the Close method on either an original object or a duplicate object made with the Clone method doesn't affect either object.


See Also

Clone Method

Delete Method

OpenDatabase Method

OpenRecordset Method

Update Method


Close Method Applies To

Database Object

Dynaset Object

QueryDef Object

Recordset Object

Snapshot Object

Table Object

Workspace Object


Delete Method

See Also	Example	Applies To

Recordset objects [image] deletes the current record in an open dynaset-type or table-type Recordset object.  The Delete method can also be used with the outdated Dynaset and Table objects.

Collections [image] deletes a stored object from a collection.

Syntax

recordset.Delete

collection.Delete objectname

The Delete method syntax has these parts:

Part	Description

recordset	A variable of an object data type identifying an open dynaset-type or table-type Recordset, Table, or Dynaset object containing the record you want to delete.

collection	A variable of an object data type identifying a collection.

objectname	A String that is the Name property setting of an object in collection.

Remarks

You can use the Delete method to delete a current record from a recordset, a member from a collection, a stored table from a database, a stored field from a table, and a stored index from a table.

Recordsets:  When you delete records from a recordset, there must be a current record in recordset before you use Delete; otherwise, a trappable error occurs.

In table-type Recordset, Table, dynaset-type Recordset, and Dynaset objects, Delete removes the current record and makes it inaccessible.  Although you can't edit or use the deleted record, it remains current.  Once you move to another record, however, you can't make the deleted record current again.  Subsequent references to a deleted record in a Recordset or Table object are invalid and produce an error.

You can undelete a record if you use transactions and the Rollback method.

If the base table is the primary table in a cascade delete relationship, deleting the current record may also delete one or more records in a foreign table.

Collections:  You can use the Delete method to delete a persistent object.  However, if the collection is a Databases, Recordsets, or Workspaces collection (each of which is stored only in memory), you can remove an open or active object by closing that object using the Close method.

The deletion of a stored object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

When you delete a TableDef object from the TableDefs collection, you delete the table definition and the data in the table.


The following table shows some limitations on the use of the Delete method.  The object in the first column contains the collection in the second column.  The third column indicates when, if ever, you can delete an object from that collection (for example, you can never delete a Container object from the Containers collection of a Database object).

Object	Collection	When can use Delete method
DBEngine	Workspaces	Never; use the Close method instead
Workspace	Databases	Never; use the Close method instead
Database	Containers	Never
Database	Recordsets	Never; use the Close method instead
Container	Documents	Never
Index	Fields	On new objects that haven't been appended to the database.
QueryDef	Fields	Never
QueryDef	Parameters	Never
Recordset	Fields	Never
Relation	Fields	On new objects that haven't been appended to the database.
TableDef	Fields	On new objects that haven't been appended to the database or when the Updatable property of the TableDef is set to True
TableDef	Indexes	On new objects that haven't been appended to the database or when the Updatable property of the TableDef is set to True
Database, Field, Index, QueryDef, TableDef	Properties	When the property is user-defined
Caution   If you use any of the DAO editing methods (AddNew, Edit, Delete, or Update) within a loop that will edit more than one record, the Jet engine version 3.0 may treat the entire loop as an implicit transaction.  This means that you will not necessarily be able to guarantee that each update is immediately written to the database.  This may affect error handling, page locking, and the immediate visibility of the changes to other users.  To guarantee that changes are immediately written to the database, enclose each Edit . . . Update block within an explicit transaction.  For more information about transactions, see the BeginTrans, CommitTrans, Rollback methods.


See Also

AddNew Method

Append Method

BeginTrans, CommitTrans, Rollback Methods

Close Method

Count Property (Data Access)

Dynaset Object

Name Property (Data Access)

Recordset Object, Recordsets Collection

Refresh Method (Data Access)

Table Object


Delete Method Applies To

Data Access Objects and Collections

Dynaset Object

Recordset Object (dynaset- and table-type only)

Table Object


Edit Method

See Also	Example	Applies To

Copies the current record from a dynaset-type or table-type Recordset object to the copy buffer for subsequent editing.  The Edit method can also be used with the outdated Dynaset and Table objects.

Syntax

recordset.Edit

The recordset placeholder represents the name of an open, updatable Recordset object that contains the record you want to edit.

Remarks

Once you use the Edit method, changes made to the current record's fields are copied to the copy buffer.  After you make the desired changes to the record, use the Update method to save your changes.

Caution   If you edit a record and then perform any operation that moves to another record without first using Update, your changes are lost without warning.  In addition, if you close recordset or end the procedure which declares the recordset or the parent Database object, your edited record is discarded without warning.

When the Recordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the updating is complete.  If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it's updated in the database.  If the record has changed since you used the Edit method, the Update operation fails with a trappable error (3197).

Note   Optimistic locking is always used on external database formats, such as ODBC and installable ISAM.

The current record remains current after you use Edit.

To use Edit, there must be a current record.  If there is no current record or if recordset doesn't refer to an open table-type or dynaset-type Recordset, a Table object, or a Dynaset object, an error occurs.

Using Edit produces an error under 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.

Another user has locked the page containing your record.

Caution   If you use any of the DAO editing methods (AddNew, Edit, Delete, or Update) within a loop that will edit more than one record, the Jet engine version 3.0 may treat the entire loop as an implicit transaction.  This means that you will not necessarily be able to guarantee that each update is immediately written to the database.  This may affect error handling, page locking, and the immediate visibility of the changes to other users.  To guarantee that changes are immediately written to the database, enclose each Edit . . . Update block within an explicit transaction.  For more information about transactions, see the BeginTrans, CommitTrans, Rollback methods.


See Also

AddNew Method

Delete Method

Dynaset Object

LockEdits Property

Recordset Object, Recordsets Collection

Table Object

Update Method


Edit Method Applies To

Dynaset Object

Recordset Object (dynaset- and table-type only)

Table Object


FindFirst, FindLast, FindNext, FindPrevious Methods

See Also	Example	Applies To

Locates the first, last, next, or previous record in a dynaset- or snapshot-type Recordset object that satisfies the specified criteria and makes that record the current record.  The Find methods can also be used with the outdated Dynaset and Snapshot objects.

Syntax

recordset.{FindFirst | FindLast | FindNext | FindPrevious} criteria

The Find methods have these parts:

Part	Description

recordset	The name of an existing dynaset- or snapshot-type Recordset, Dynaset, or Snapshot object.

criteria	A string expression (like the WHERE clause in an SQL statement without the word WHERE) used to locate the record.

Remarks

If you want to include all the records in your search [image] not just those that meet a specific condition [image] use the Move methods to move from record to record.  To locate a record in a table-type Recordset, use the Seek method.

If a record matching the criteria isn't located, the current record pointer is positioned to the first record in the Recordset, and the NoMatch property is set to True.  If recordset contains more than one record that satisfies the criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.

Caution   If you edit the current record, be sure you save the changes using the Update method before you move to another record.  If you move to another record without updating, your changes are lost without warning.

Each of the Find methods begins its search from the location and in the direction specified in the following table:

Find methods	Begin	Search direction
FindFirst	Beginning of recordset	End of recordset
FindLast	End of recordset	Beginning of recordset
FindNext	Current record	End of recordset
FindPrevious	Current record	Beginning of recordset
When you use the FindLast method, the Microsoft Jet database engine fully populates your recordset before beginning the search [image] if this hasn't already been done.

Using one of the Find methods isn't the same as using a Move method, however, which simply makes the first or next record current without specifying a condition.  You can follow a Find operation with a Move operation.

Note   Always check the value of the NoMatch property to determine whether the Find operation has succeeded.  If the search succeeds, NoMatch is set to False.  If it fails, NoMatch is set to True and the current record is set to the first record in the Recordset.  For example:

Dim Here as Variant

Here = Rs.Bookmark

Rs.FindFirst "Name = 'Ms. Schmidt' "	' Search for a name in the recordset.

If Rs.NoMatch then 	' Was it not found?

Rs.Bookmark = Here	' If not found, go back to previously

' current record.

Else

. 	' Match found.

.

.

End If

You can't use these methods with a forward-only scrolling snapshot-type Recordset.

Using the Find methods with ODBC-accessed recordsets can be inefficient.  You may find that rephrasing your SQL to locate a specific record is faster, especially when working with large recordsets.

You should use the U.S. date format (month-day-year) when you search for fields containing dates, even if you're not using the U.S. version of the Jet database engine; otherwise, the data may not be found.  Use the Format function to convert the date.  For example:

MyDs.FindFirst "statdate > #" & Format(mydate, 'm/d/yy' ) & "#"

When working with ODBC databases and large dynasets, you may discover that using the Find methods or using the Sort or Filter properties is slow.  You can improve performance by using SQL queries with customized ORDER BY or WHERE clauses, parameter queries, or QueryDef objects that retrieve specific indexed records.

Note   You can't use the Find methods with forward-only-scrolling snapshots.


See Also

AbsolutePostion Property

Dynaset Object

Move Method (Data Access)

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

NoMatch Property

PercentPosition Property

Recordset Object, Recordsets Collection

Seek Method

Snapshot Object


FindFirst, FindLast, FindNext, FindPrevious Methods Apply To

Dynaset Object

Recordset Object

Snapshot Object


MoveFirst, MoveLast, MoveNext, MovePrevious Methods

See Also	Example	Applies To

Move to the first, last, next, or previous record in a specified Recordset object and make that record the current record.  The Move methods can also be used with the outdated Dynaset, Snapshot, and Table objects.

Syntax

object.{MoveFirst | MoveLast | MoveNext | MovePrevious}

The object placeholder represents an object expression that evaluates to the name of an open Recordset, Dynaset, Table, or Snapshot object.

Remarks

Use the Move methods to move from record to record without applying a condition.  Use the Find methods to locate records in a dynaset- or snapshot-type Recordset, Dynaset, or Snapshot object that satisfy a certain condition.  To locate a record in a table-type Recordset or a Table object, use the Seek method.

Caution   If you edit the current record, be sure you save the changes using the Update method before you move to another record.  If you move to another record without updating, your changes are lost without warning.

When you open the recordset named by recordset, the first record is current and the BOF property is set to False.  If the recordset contains no records, the BOF property is set to True, and there is no current record.

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

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

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

If recordset refers to a table-type Recordset or Table object, movement follows the table's current index.  You can set the current index using the Index property.  If you don't set the current index, the order of returned records is undefined.

If you use MoveLast on a Recordset object based on an SQL query or QueryDef, the query is forced to completion and the Recordset object is fully populated.

Notes

You can't use the MoveFirst or MovePrevious method with a forward-only scrolling snapshot.

To move the position of the current record in a Recordset object a specific number of records forward or backward, use the Move method.


See Also

AbsolutePostion Property

BOF, EOF Properties

Dynaset Object

FindFirst, FindLast, FindNext, FindPrevious Methods

Index Property (Data Access)

Move Method (Data Access)

PercentPosition Property

QueryDef Object, QueryDefs Collection

RecordCount Property

Recordset Object, Recordsets Collection

Seek Method

Snapshot Object

Table Object

Update Method (Data Access)


MoveFirst, MoveLast, MoveNext, MovePrevious Methods Apply To

Dynaset Object

Recordset Object, Recordsets Collection

Snapshot Object

Table Object


GetChunk Method

See Also	Example	Applies To

Returns all or a portion of the contents of a Memo or an OLE Object Field object in the Fields collection of a Recordset object.  You can also use the GetChunk method on the fields of the outdated Dynaset, Snapshot, and Table objects.

Syntax

stringvar = recordset ! field.GetChunk(offset, numbytes)

The GetChunk method syntax has these parts:

Part	Description

stringvar	The name of a String variable or Variant that receives the data from the Field object named by field.

recordset	A variable of an object data type that specifies the Recordset, Table, Dynaset, or Snapshot object containing the Fields collection.

field	The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.

offset	A numeric expression that is the number of bytes to skip before copying begins.

numbytes	A numeric expression that is the number of bytes you want to return.

Remarks

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

Assign the bytes returned by GetChunk to stringvar.  Because a String variable is limited in size, numbytes can't be greater than approximately 64K.  If the field is greater than 64K, use GetChunk to return a portion at a time.  You can use the AppendChunk method to reassemble the pieces.  If numbytes is greater than 64K, an error occurs even if stringvar is a Variant.

If numbytes is greater than the number of bytes in the field, the actual number of bytes in the field is returned.  After assigning the results of GetChunk to a String variable, you can use the Len function to determine the number of bytes returned.

If the value of offset or numbytes is less than 0, GetChunk uses the two's complement of the value.


See Also

AppendChunk Method

Dynaset Object

Field Object, Fields Collection

FieldSize Method

Len Function

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

Type Property (Data Access)


GetChunk Method Applies To

Field Object


FieldSize Method

See Also	Example	Applies To

Returns the number of bytes in a Memo or an OLE Object Field object in the Fields collection of a Recordset object.  The FieldSize method can also be used on the fields of the outdated Dynaset, Snapshot, and Table objects.

Syntax

varname = recordset ! field.FieldSize( )

The FieldSize method syntax has these parts:

Part	Description

varname	The name of a Long or Variant variable.

recordset	A variable of an object data type that specifies the Recordset, Table, Dynaset, or Snapshot object containing the Fields collection.

field	The name of a Field object whose Type property is set to dbMemo (Memo), dbLongBinary (OLE Object), or the equivalent.

Remarks

Because the size of an OLE Object field or Memo field can exceed 64K, you should assign the value returned by FieldSize to a variable large enough to store a Long variable.

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

Note   To determine the size of a Field object (except Memo and Long Binary types), use the Size property.


See Also

AppendChunk Method

Dynaset Object

Field Object, Fields Collection

GetChunk Method

Recordset Object, Recordsets Collection

Size Property (Data Access)

Snapshot Object

Table Object

Type Property (Data Access)


FieldSize Method Applies To

Field Object


Update Method (Data Access)

See Also	Example	Applies To

Saves the contents of the copy buffer to a specified dynaset- or table-type Recordset object.  You can also use the Update method with the outdated Dynaset and Table objects.

Syntax

recordset.Update

The recordset placeholder represents the name of an open, updatable dynaset- or table-type Recordset, Dynaset, or Table object.

Remarks

Use Update to save the current record and any changes you've made to it.

Caution   Changes to the current record are lost if:

You use the Edit or AddNew method, and then move to another record without first using Update.

You use Edit or AddNew, and then use Edit or AddNew again without first using Update.

You set the Bookmark property to another record.

You close the recordset referred to by recordset without first using Update.

To edit a record, use the Edit method to copy the contents of the current record to the copy buffer.  If you don't use Edit first, an error occurs when you use Update or attempt to change a field's value.

When the Recordset object's LockEdits property setting is True (pessimistically locked) in a multiuser environment, the record remains locked from the time Edit is used until the Update method is executed.  If the LockEdits property setting is False (optimistically locked), the record is locked and compared with the pre-edited record just before it is updated in the database.  If the record has changed since you used the Edit method, the Update operation fails with a trappable error (3197).  Note that optimistic locking is always used on external database formats like ODBC or installable ISAM.  To continue the Update operation with your changes, use the Update method again.  To revert to the record as the other user changed it, refresh the current record using the Move methods, or set the Bookmark property to itself.  For example:

' Error 3197 detected

Rs.BookMark = Rs.Bookmark	' Restore record from

' database (as changed).

To add a new record to a recordset, use the AddNew method.

Caution   If you use any of the DAO editing methods (AddNew, Update, Edit, or Update) within a loop that will edit more than one record, the Jet engine version 3.0 may treat the entire loop as an implicit transaction.  This means that you will not necessarily be able to guarantee that each update is immediately written to the database.  This may affect error handling, page locking, and the immediate visibility of the changes to other users.  To guarantee that changes are immediately written to the database, enclose each Edit . . . Update block within an explicit transaction.  For more information about transactions, see the BeginTrans, CommitTrans, Rollback methods.


See Also

AddNew Method

BeginTrans, CommitTrans, Rollback Methods

Dynaset Object

Edit Method

LockEdits Property

OpenRecordset Method

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

UpdateControls Method

UpdateRecord Method


Update Method Applies To

Dynaset Object

Recordset Object (dynaset- and table-type only)

Table Object


CreateQueryDef Method

See Also	Example	Applies To

Creates a new QueryDef object in a specified database.

Syntax

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

The CreateQueryDef method syntax has these parts:

Part	Description

querydef	A variable of an object data type that represents the QueryDef object you want to create.

database	A variable of an object data type that represents the open Database object that contains the new QueryDef.

name	A string expression that is the name of the new QueryDef.

sqltext	A string expression (a valid SQL statement) that defines the QueryDef.  If you omit this argument, you can define the QueryDef by setting its SQL property before or after you append it to a collection.

Remarks

If you include name but omit sqltext or include both name and sqltext, the QueryDef is automatically saved when you create or change it.

If the object specified by name is already a member of the QueryDefs collection, a trappable error occurs.

You can create a temporary QueryDef by setting the Name property of a newly created QueryDef to a zero-length string ("") or by using a zero-length string for the name argument when you execute the CreateQueryDef method.  You can't append a temporary QueryDef to any collection because a zero-length string isn't a valid name for a permanent QueryDef.  You can set the Name and SQL properties of the newly created QueryDef and subsequently append the QueryDef to the QueryDefs collection where it's stored in the database.  If you provide anything other than a zero-length string for the name when you create a QueryDef, the resulting QueryDef object is automatically appended to the QueryDefs collection.

To remove a QueryDef object from a QueryDefs collection, use the Delete method on the collection.

To run the SQL statement in a QueryDef object, use the Execute method.

Using a QueryDef object is the preferred way to perform SQL pass-through queries with ODBC databases.  See the QueryDef object for more information.


See Also

Append Method

Connect Property

CreateProperty Method

Database Object, Databases Collection

Delete Method

DROP Statement (SQL)

Execute Method

LogMessages Property

Name Property (Data Access)

OpenRecordset Method

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

ReturnsRecords Property

SELECT...INTO SQL Statement

SQL Property

Using SQL PassThrough

Type Property (Data Access)

Value Property (Data Access)


CreateQueryDef Method Applies To

Database Object


DeleteQueryDef Method

See Also	Example	Applies To

Deletes a specified QueryDef object from a database.

Note   The DeleteQueryDef method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you use the Delete method of the QueryDefs collection instead.  For more information, see Examples of Converting Code to Jet Version 2.5/3.0.

Syntax

database.DeleteQueryDef name

The DeleteQueryDef method syntax has these parts:

Part	Description

database	Name of an open Database object.

name	String expression that is the name of an existing QueryDef object.

Remarks

Once you use DeleteQueryDef, subsequent references to name are invalid and produce a trappable error.

If the QueryDef named by name doesn't exist or is open or if database doesn't refer to an open database, an error occurs.


See Also

Delete Method


DeleteQueryDef Method Applies To

Database Object


ListFields Method

See Also	Applies To

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

Note   The ListFields method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you instead enumerate the Fields collection of the object containing the fields you want to list.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax 1

Set snapshot = recordset.ListFields( )

Syntax 2

Set snapshot = database.ListFields(table | query)

The ListFields method syntax has the following parts:

Part	Description

snapshot	The object variable of the Snapshot object you want to create.

recordset	The name of an existing Dynaset, Snapshot, or Table object that contains the fields you want to list.

database	The name of an open Database object that contains the table or query fields you want to list.

table	The name of a Table object that contains the fields you want to list.

query	The name of a QueryDef object that contains the fields you want to list.


See Also

Field Object, Fields Collection

Snapshot Object

StrComp Function


ListFields Method Applies To

Database Object

Dynaset Object

Snapshot Object


ListIndexes Method

See Also	Applies To

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

Note   The ListIndexes method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you enumerate the Indexes collection of the object containing the indexes you want to list.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax

Set snapshot = table.ListIndexes( )

The ListIndexes method syntax has these parts:

Part	Description

snapshot	Object variable for the Snapshot object you want to create.

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


ListIndexes Method Applies To

Table Object


See Also

Field Object, Fields Collection

Indexes Collection

InStr Function

Snapshot Object

StrComp Function

TableDef Object


OpenQueryDef Method

See Also	Example	Applies To

Opens a specified QueryDef object for subsequent editing.

Note   The OpenQueryDef method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you use the QueryDefs collection, SQL property, or the Parameters collection of a QueryDef object instead.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax

Set querydef = database.OpenQueryDef(name)

The OpenQueryDef method syntax has these parts:

Part	Description

querydef	Name of the QueryDef you want to use during editing.

database	Name of an open Database object.

name	String expression that is the name of an existing QueryDef.

Remarks

If the QueryDef contains parameters, you must provide the corresponding arguments before running the query.  The parameter settings are dependent upon the data type of the parameters.  An Integer parameter requires an argument that is also an Integer, a Double requires an argument that is also a Double, and so on.  If a parameter isn't set prior to run time, an error occurs.

The following example sets a parameter named FindAmount:

MyQuery!FindAmount = 1000

If name refers to a QueryDef that doesn't exist, an error occurs.


See Also

Database Object, Databases Collection

Parameter Object, Parameters Collection

QueryDef Object, QueryDefs Collection

SQL Property


OpenQueryDef Method Applies To

Database Object


Seek Method

See Also	Example	Applies To

Locates the record in an indexed table-type Recordset object that satisfies the specified criteria for the current index and makes that record the current record.  The Seek method can also be used with the outdated Table object if an index is defined for it.

Syntax

table.Seek comparison, key1, key2...

The Seek method syntax has the following parts:

Part	Description

table	The name of an existing table-type Recordset object or Table object that has a defined index as specified by the Recordset or Table object's Index property.

comparison	One of these string expressions: "<", "<=", "=", ">=", or ">".

key1, key2...	One or more values corresponding to the underlying table's Primary property setting.

Remarks

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 that satisfies the criteria.

Caution   If you edit the current record, be sure you save the changes using the Update method before you move to another record.  If you move to another record without using Update, your changes are lost without warning.

The Seek method searches through the specified key fields and locates the first record that satisfies the criteria specified by comparison and key1.  Once found, it makes that record current and the NoMatch property is set to False.  If the Seek method fails to locate a match, the NoMatch property is set to True, and the current record is undefined.

If comparison is "=",  ">=", or  ">", Seek starts at the beginning of the index.  If comparison is "<" or "<=", Seek starts at the end of the index and searches backward unless there are duplicate index entries at the end.  In this case, Seek starts at an arbitrary entry among the duplicate index entries at the end of the index.

The key1 argument 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 number field (such as Employee ID), key1 must be numeric.  Similarly, if the current index refers to a Text field (such as Last Name), key1 must be a string.

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

You can use the Indexes collection to enumerate the existing indexes.

Notes

Always check the value of the NoMatch property setting to determine whether the Seek method has succeeded.  If it fails, NoMatch is set to True and the current record is undefined.

To locate a record in a dynaset- or snapshot-type Recordset that satisfies a specific condition, use the Find methods.  To include all records, not just those that satisfy a specific condition, use the Move methods to move from record to record.

You can't use the Seek method on an attached table of any type because attached tables must be opened as dynaset- or snapshot-type Recordset, Dynaset, or Snapshot objects, which don't support the Seek method.  However, if you use the OpenDatabase method to directly open an installable ISAM database, you can use Seek on tables in that database.


See Also

Absolute Postion Property

BOF, EOF Properties

FindFirst, FindLast, FindNext, FindPrevious Methods

Index Object, Indexes Collection

Index Property (Data Access)

Move Method (Data Access)

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

NoMatch Property

OpenDatabase Method

PercentPosition Property

Recordset Object, Recordsets Collection

Table Object


Seek Method Applies To

Recordset Object (table-type only)

Table Object


Append Method

See Also	Example	Applies To

Adds a new data access object to a collection.

Syntax

collection.Append object

The Append method syntax has these parts:

Part	Description

collection	Any collection that can accept new objects (for limitations, see the following table).

object	A variable of an object data type identifying the object being appended, which must be of the same type as the elements of collection.

Remarks

Uses of the Append method include adding a new table to a database, adding a field to a table, and adding a field to an index.

The appended object becomes a persistent object, stored on disk, until you delete it using the Delete method.  If the collection is a Workspaces collection (which is stored only in memory), the object is active until you remove it using the Close method.

The addition of a new object occurs immediately, but you should use the Refresh method on any other collections that may be affected by changes to the database structure.

If the object being appended isn't complete (such as when you haven't appended any Field objects to a Fields collection before it's appended to an Indexes collection) or if the properties set in one or more subordinate objects are incorrect, the Append method triggers a trappable error.  For example, if you specify an invalid field type and then try to append the Field object to the Fields collection in a TableDef object, the Append method triggers a trappable error.

The following table shows some limitations on the use of the Append method.  The object in the first column is an object containing the collection in the second column.  The third column indicates when, if ever, you can append an object to that collection (for example, you can never append a Container object to the Containers collection of a Database object).

Object	Collection	When can use Append
Workspace	Databases	Never; use the OpenDatabase method instead
Database	Containers	Never
Database	Recordsets	Never; use the OpenRecordset method instead
Container	Documents	Never
Index	Fields	When the Index object is a new, unappended object
QueryDef	Fields	Never
QueryDef	Parameters	Never
Recordset	Fields	Never
Relation	Fields	Never
TableDef	Fields	When the Updatable property of the TableDef is set to True
TableDef	Indexes	When the Updatable property of the TableDef is set to True
Database, Field, Index, QueryDef, TableDef	Properties	When the Database, Field, Index, QueryDef, or TableDef is persistent


See Also

Close Method

Count Property (Data Access)

Delete Method

Refresh Method


Append Method Applies To

Containers Collection

Databases Collection

Documents Collection

Fields Collection

Groups Collection

Indexes Collection

Parameters Collection

Properties Collection

QueryDefs Collection

Recordsets Collection

Relations Collection

TableDefs Collection

Users Collection


CreateDynaset Method

See Also	Example	Applies To

Creates a Dynaset object from a specified Dynaset object, Table object, QueryDef object, or SQL statement.

Note   The CreateDynaset method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you use the OpenRecordset method, which creates a dynaset-type Recordset.  The outdated Dynaset object created with CreateDynaset is different from the dynaset-type Recordset object.  Although both have similar properties and methods, the dynaset-type Recordset supports significant additional functionality.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax

Set dynasetobject = database.CreateDynaset( source [, options ] )

Set dynasetobject = { recordset | querydef }.CreateDynaset( [ options ] )

The CreateDynaset method syntax has these parts:

Part	Description

dynasetobject	Object variable of type Dynaset.

database	Object variable identifying an open database.

recordset	Object variable identifying an existing Dynaset or Table object.

querydef	Object variable identifying an existing QueryDef object.

source	String expression that is the name of an existing recordset, QueryDef object, or SQL statement.

options	A numeric expression indicating one or more options, as defined in Settings.  Values can be combined by adding them together.

Settings

You can supply one or a combination of the following constants and values in the options part:

Constant	Value	Description

dbDenyWrite	1	In a multiuser or multitasking environment, others can't make changes to any records in any table in your Dynaset while you have it open.  Use for administrative purposes only.

dbReadOnly	4	You can't make changes to records in your Dynaset.  This can increase the speed of some operations.

dbAppendOnly	8	You can only add new records to the Dynaset.  You can't read or update existing records.

dbInconsistent	16	Updates can apply to all fields of the Dynaset, even if they also affect other rows of the Dynaset.

dbConsistent	32	(Default) Updates apply only to those fields that won't affect other rows of the Dynaset.

dbSQLPassThrough	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 database.  The Dynaset isn't updatable.  You may find it more efficient to use a snapshot-type Recordset object or a Snapshot object instead of a Dynaset object with an SQL PassThrough.  Ignored except for ODBC remote databases.

Note   You cannot use the CreateDynaset method to execute an SQLPassThrough query that does not return records.  This functionality is supported in Visual Basic version 3.0, but not in version 4.0.

If both dbInconsistent and dbConsistent are included or if neither are included, the result is the default.

Remarks

When used on a Dynaset or Snapshot, CreateDynaset returns a new Dynaset object containing records filtered and sorted according to the Filter and Sort properties of the Dynaset or Snapshot object.  CreateDynaset doesn't affect the contents of the first Dynaset or Snapshot.  Use of these properties isn't recommended for large recordsets.  It's more efficient to create an SQL query with an amended WHERE or ORDER BY clause.

Dynaset objects can be used with SQL PassThrough operations; however, only one set of results returns from the query, and all messages are discarded.  Using the QueryDef object enables you to run queries that return more than one set of results and messages.

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 reflects changes made by others while you are using it.  A Snapshot doesn't.

Note   If your program requires two identical Dynasets, it's more efficient to create a single Dynaset and then use the Clone method to create a second reference.


See Also

Clone Method

CreateQueryDef Method

CreateSnapshot Method

Filter Property

OpenRecordset Method

OpenTable Method

Options Property

Or Operator

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Sort Property


CreateDynaset Method Applies To

Database Object

Dynaset Object

QueryDef Object, QueryDefs Collection

Snapshot Object

Table Object


CreateSnapshot Method

See Also	Example	Applies To

Creates a Snapshot object from a specified table, QueryDef object, or SQL statement.

Note   The CreateSnapshot method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you use the OpenRecordset method which creates a snapshot-type Recordset object.  The outdated Snapshot object created with CreateSnapshot is different from the snapshot-type Recordset object.  Although both have similar properties and methods, the snapshot-type Recordset supports significant additional functionality.  For more information, see Converting Code to the Jet Database Engine Version 2.5.

Syntax

Set snapshot = database.CreateSnapshot( source [, options ] )

Set snapshot = recordset|querydef.CreateSnapshot( [ options ] )

The CreateSnapshot method has these parts:

Part	Description

snapshot	An object variable of type Snapshot.

database	Object variable identifying an open database.

recordset	Object variable identifying an existing Dynaset, Snapshot, or Table object.

querydef	Object variable identifying an existing QueryDef object.

source	String expression that is the name of an existing recordset, QueryDef object, or SQL statement.

options	A numeric expression indicating one or more option settings, as defined in Settings.  Values can be combined by adding them together.

Settings

You can use one or a combination of the following constants and values in the options part:

Constant	Value	Description

dbDenyWrite	1	In a multiuser environment, others can't make changes to records in any table in your Snapshot while you have it open.  Use for administrative purposes only.

dbSQLPassThrough	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 database.  Ignored except for ODBC remote databases.

Note   You cannot use the CreateSnapshot method to execute an SQLPassThrough query that does not return records.  This functionality is supported in Visual Basic version 3.0, but not in version 4.0.

Remarks

Unlike the data in a Dynaset, the data in a Snapshot isn't linked to its underlying tables so the data in a Snapshot doesn't change even if the data in its underlying tables changes.  Furthermore, you can't change the data in a Snapshot.

When used on a Dynaset or Snapshot, CreateSnapshot returns a Snapshot containing records filtered and sorted according to the Filter and Sort properties of the Dynaset or Snapshot object.  The contents of the original Dynaset or Snapshot isn't affected.

When used on a QueryDef object, CreateSnapshot runs the QueryDef and returns a Snapshot that is a copy of the data defined by the QueryDef.  If you use CreateSnapshot on a QueryDef containing an action query, an error occurs (use the Execute method in this case).

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, not change data, a Snapshot object is faster than a read-only Dynaset object.  However, a read-only Dynaset reflects changes made by others while you are using it.  A Snapshot doesn't.


See Also

CreateDynaset Method

Dynaset Object

Execute Method

Field Object, Fields Collection

OpenRecordset Method

Options Property

Or Operator

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Snapshot Object

Sort Property

Table Object

TableDefs Collection


CreateSnapshot Method Applies To

Database Object

Dynaset Object

QueryDef Object, QueryDefs Collection

Snapshot Object

Table Object


Execute Method

See Also	Example	Applies To

Runs an action query or executes an SQL statement on a specified Database object.

Syntax

database.Execute source[, options]

querydef.Execute [options]

For a Database object, the Execute method syntax has these parts:

Part	Description

database	The name of the Database object on which the query will run.

source	The SQL statement or QueryDef object.

options	An integer constant that determines the data integrity characteristics of the query, as specified in Settings.

For a QueryDef object, the Execute method syntax has these parts:

Part	Description

querydef	The name of the QueryDef object whose SQL property setting specifies the SQL statement to execute.

options	An integer or constant that determines the data integrity characteristics of the query, as specified in Settings.

Settings

You can use the following constants for the options part:

Constant	Description

dbDenyWrite	Deny write permission to other users.

dbInconsistent	(Default) Inconsistent updates.

dbConsistent	Consistent updates.

dbSQLPassThrough	SQL pass-through.  Causes the SQL statement to be passed to an ODBC  database for processing.

dbFailOnError	Roll back updates if an error occurs.

dbSeeChanges	Generate a run-time error if another user is changing data you are editing.

Remarks

The Execute method is valid only for action queries.  If you use Execute with another type of query, an error occurs.  Because an action query doesn't return any records, Execute doesn't return a recordset.

Tips

Given a syntactically correct SQL statement and proper permissions, the Execute method won't fail [image] even if not a single row can be modified or deleted.  Therefore, always use the dbFailOnError option when using the Execute method to run an update or delete query.  This option generates a trappable error and rolls back all successful changes if any of the records affected are locked and can't be updated or deleted.

For best performance, especially in a multiuser environment, nest the Execute method inside a transaction:  Use the BeginTrans method on the current Workspace object, then use the Execute method, and complete the transaction by using the CommitTrans method on the Workspace.  This saves changes on disk and frees any locks that may have been placed while the query was running.

Use the RecordsAffected property of the Database or Querydef object to determine the number of records affected by the most recent Execute method.  For example, RecordsAffected contains the number of records deleted, updated or inserted when executing an action query.  When you use the Execute method to run a Querydef, the RecordsAffected property of the Querydef object is set to the number of records affected.

If both dbInconsistent and dbConsistent are included or if neither is 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 doesn't return a value.

ExecuteSQL operates only on a remote ODBC database, such as SQL Server.

Execute allows setting of options that affect how the SQL statement is executed.


See Also

Database Object, Databases Collection

ExecuteSQL Method

QueryDef Object, QueryDefs Collection

RecordsAffected Property


Execute Method Applies To

Database Object

QueryDef Object


ExecuteSQL Method

See Also	Example	Applies To

Executes an action query as an SQL statement on an ODBC database.

Note   The ExecuteSQL method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you use the OpenRecordset method which creates a snapshot-type Recordset object with QueryDef objects that contain external ODBC database SQL queries.  You can also use the Execute method with the dbSQLPassThrough option.

Syntax

rows = database.ExecuteSQL( sqlstatement )

The ExecuteSQL method syntax has these parts:

Part	Description

rows	The number of rows affected by the action query.  Long data type.

database	An object variable identifying an open Database object.

sqlstatement	A string expression that is a valid SQL statement that doesn't return a recordset.

Remarks

The ExecuteSQL method is valid only for SQL statements that don't return records.  For example, an SQL statement that uses a SELECT clause returns records, while an SQL statement that uses a DELETE clause doesn't.

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 doesn't return a value.

ExecuteSQL operates only on a remote ODBC database, such as SQL Server.

Execute allows setting of options that affect how the SQL statement is executed.

Note   The Execute method uses server resources more efficiently.  Unless you need to know the number of rows affected by the operation, it's recommended that you use the Execute method instead.


See Also

CreateQueryDef Method

Execute Method

OpenQueryDef Method

QueryDef Object

Using SQL PassThrough


ExecuteSQL Method Applies To

Database Object


ListTables Method

See Also	Applies To

Creates a Snapshot object with one record for each table or QueryDef object in a specified database.

Note   The outdated ListTables method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you examine the QueryDefs and TableDefs collections instead.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax

Set snapshot = database.ListTables( )

The ListTables method syntax has these parts:

Part	Description

snapshot	Name of the Snapshot object you want to create.

database	Name of an open Database object that contains the TableDef or QueryDef object you want to list.


See Also

QueryDef Object, QueryDefs Collection

TableDef Object, TableDefs Collection


ListTables Method Applies To

Database Object


OpenTable Method

See Also	Example	Applies To

Opens an existing database table and creates a Table object.

Note   The OpenTable method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you use the OpenRecordset method which creates table-type Recordset objects.  The outdated Table object created with OpenTable is different from the table-type Recordset object.  Although both have similar properties and methods, the table-type Recordset supports significant additional functionality.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax

Set table = database.OpenTable(name[, options])

The OpenTable method syntax has these parts:

Part	Description

table	Name of the Table object you want to use during editing.

database	Name of an open Database object.

name	String expression that is the name of an existing table in database.  It can't be the name of an attached table.

options	One or a sum of constants, as described in Settings.  If you omit this argument, shared, read/write access is enabled.

Settings

You can use these constants for the options argument:

Constant	Description

dbDenyWrite	In a multiuser or multitasking environment, other users can't make changes to any records in the table while you have it open.

dbDenyRead	In a multiuser or multitasking environment, other users can't read any records in the table while you have it open.  Use for administrative purposes only.

dbReadOnly	You can't make changes to records in the table.  Using this constant can increase the speed of some operations.

If the table is already opened for exclusive access when you use OpenTable, an error occurs.


See Also

OpenRecordset Method

Recordset Object, Recordsets Collection

Table Object


OpenTable Method Applies To

Database Object


Refresh Method (Data Access)

See Also	Applies To

Updates the objects in a collection to reflect the current database.  The Refresh method is also used to close and rebuild the Recordset object.

Syntax

collection.Refresh

Remarks

The Refresh method can't be used with collections that aren't persistent, such as Databases, Recordsets, or Workspaces.

Note   To determine the position that the Microsoft Jet database engine uses for Field objects in the Fields collection of a QueryDef, Recordset, or TableDef object, use the OrdinalPosition property of each Field object.  The Refresh method may change the order of objects within the Fields collection, if the OrdinalPosition property of a Field object in the collection has been changed.

Use the Refresh method in multiuser environments in which other users may change the database.  You may also need to use it on any collections that are indirectly affected by changes to the database.  For example, if you change a Users collection, you may need to refresh a Groups collection before using the Groups collection.

Tip   A collection is filled with objects the first time it's referred to and won't automatically reflect subsequent changes made to it by other users.  If it's likely that a collection has been changed by another user, use the Refresh method on the collection immediately before carrying out any task in your application that assumes the presence or absence of a particular object in the collection.  This will ensure that the collection is as up-to-date as possible.


See Also

Append Method

Close Method

Delete Method

OrdinalPosition Property

Requery Method


Refresh Method Applies To

Containers Collection

Documents Collection

Fields Collection

Groups Collection

Indexes Collection

Parameters Collection

Properties Collection

QueryDefs Collection

Relations Collection

TableDefs Collection

Users Collection


BeginTrans, CommitTrans, Rollback Methods

See Also	Example	Applies To

The transaction methods manage transaction processing during a session defined by a Workspace object as follows:

BeginTrans begins a new transaction.

CommitTrans ends the current transaction and saves the changes.

Rollback ends the current transaction and restores the databases in the Workspace object to the state they were in when the current transaction began.

You can use the transaction methods with a Database object; however, this isn't recommended because these Database methods are outdated.

Syntax

workspace.BeginTrans | CommitTrans | Rollback

database.BeginTrans | CommitTrans | Rollback

The transaction methods have these parts:

Part	Description

workspace	A variable of an object data type identifying the Workspace.

database	A variable of an object data type identifying the Database.

Remarks

You use these methods with a Workspace or Database object when you want to treat a series of changes made to the databases in a session as one unit.

Note   All of the transaction methods apply to the Workspace specified.  If you use the methods with a Database object, the method applies to the Database object's Workspace.  If you use the transaction statements, the default Workspace is used; however, this technique is discouraged.

Typically, you use transactions to maintain the integrity of your data when you must update records in two or more tables and ensure that changes made are completed (committed) in all tables or none at all (rolled back).  For example, if you transfer money from one account to another, you might subtract an amount from one and add the amount to another.  If either update fails, the accounts no longer balance.  Use the BeginTrans method before updating the first record, and then, if any subsequent update fails, you can use the Rollback method to undo all of the updates.  Use the CommitTrans method after you successfully update the last record.

Caution   Within one Workspace object, transactions are always global to the Workspace and aren't limited to only one database or recordset.  If you perform operations on more than one database or recordset within a Workspace transaction, the Rollback method restores all operations on those databases and recordsets.

Once you use CommitTrans, you can't undo changes made during that transaction unless the transaction is nested within another transaction that is itself rolled back.  You can have up to five levels of transactions open at once in a single Workspace object by using multiple, nested combinations of BeginTrans and CommitTrans or Rollback.  If you nest transactions, you must save or roll back the current transaction before you can save or roll back a transaction at a higher level of nesting.  If you want to have simultaneous transactions with overlapping, non-nested scopes, you can create additional Workspace objects to contain the concurrent transactions.

If you close a Workspace object without saving or rolling back any pending transactions, the transactions are automatically rolled back.

If you use the CommitTrans or Rollback methods without first using the BeginTrans method, an error occurs.

Some databases may not support transactions, in which case the Transactions property of the Database object or Recordset object is False.  To make sure that the database supports transactions, check the value of the Transactions property of the Database object before using the BeginTrans method.  If you are using a Recordset object based on more than one database, check the Transactions property of the Recordset object.  If a recordset is based entirely on Microsoft Jet database engine tables, its Transactions property is True (-1), and you can use transactions.  Dynaset-type Recordset objects based on tables created by other database products, however, may not support transactions.  For example, you can't use transactions in a Recordset based on a Paradox table.  In this case, the Transactions property is False (0).  If the Database or Recordset doesn't support transactions, the methods are ignored and no error occurs.

When using external ODBC SQL databases, you can't nest transactions.

If you use any of the DAO editing methods (AddNew, Update, Edit, or Update) within a loop that will edit more than one record, the Jet engine version 3.0 may treat the entire loop as an implicit transaction.  This means that you will not necessarily be able to guarantee that each update is immediately written to the database.  This may affect error handling, page locking, and the immediate visibility of the changes to other users.  To guarantee that changes are immediately written to the database, enclose each Edit . . . Update block within an explicit transaction, as shown in the following example:

While NOT RS.EOF

WS.BeginTrans

RS.Edit

. . .	'Make some changes

RS.Update

WS.CommitTrans

RS.Movenext

WEND

Tip   In addition to performing transactions to maintain data integrity, you can often improve the performance of your application by breaking operations that require disk access on your database into transaction blocks.  This ensures buffering of your operations and may greatly reduce the number of times a disk is accessed.

Note   When you begin a transaction, the Jet database engine records its operations in a file kept in the directory specified by the TEMP environment variable on the workstation.  If the transaction log file exhausts the available storage on your TEMP drive, the Jet database engine will trigger a trappable error (2004).  At this point, if you use a CommitTrans, an indeterminate number of operations are committed but the remaining uncompleted operations are lost, and the operation has to be restarted.  Using a Rollback method releases the transaction log and rolls back all operations in the transaction.


See Also

Close Method

DefaultUser, DefaultPassword Properties

CreateWorkspace Method

Database Object, Databases Collection

Recordset Object, Recordsets Collection

Refresh Method

Workspace Object, Workspaces Collection


BeginTrans, CommitTrans, Rollback Methods Apply To

Database Object

Workspace Object


Clone Method

See Also	Example	Applies To

Creates a duplicate Recordset object that refers to the original object.  You can also use the Clone method with the outdated Dynaset, Snapshot, and Table objects.

Syntax

Set duplicate = original.Clone( )

The Clone method syntax has these parts:

Part	Description

duplicate	A variable of an object data type identifying the duplicate Recordset, Dynaset, Snapshot, or Table object you're creating.

original	A variable of an object data type identifying the Recordset, Dynaset, Snapshot, or Table object you want to duplicate.

Remarks

Use the Clone method to create multiple, duplicate recordsets (Recordset, Dynaset, Snapshot, and Table objects).  Each recordset can have its own current record.  Using Clone by itself doesn't change the data in the objects or in their underlying structures.  Using the Clone method, you can share bookmarks between two or more recordsets because their bookmarks are interchangeable.

Note   When used on a table-type Recordset object, the Index property setting is not cloned on the new copy of the Recordset.  You must copy the Index property setting manually.

You could use Clone when you want to perform an operation on a recordset that requires multiple current records.  This is faster and more efficient than creating a second recordset.

A recordset you create with Clone initially lacks a current record.  To make a record current before you use the recordset object specified by duplicate, you must set the Bookmark property or use one of the Move methods, one of the Find methods (for dynaset- and snapshot-type Recordset, Dynaset and Snapshot objects only), or the Seek method (for table-type Recordset and Table objects only).

Cloning a recordset that resulted from running a QueryDef object doesn't run the query again.

Using the Close method on either the original or duplicate object doesn't affect the other object.

Note   You can't use this method with forward-scrolling snapshots (snapshot-type Recordset objects that have the dbForwardOnly option set).


See Also

Bookmark Property

Dynaset Object

Recordset Object, Recordsets Collection


Clone Method Applies To

Dynaset Object

Recordset Object

Snapshot Object

Table Object


ListParameters Method

See Also	Applies To

Creates a Snapshot object with one record for each parameter in a specified QueryDef object.

Note   The ListParameters method is included in this version for compatibility with earlier versions of Visual Basic.  It's recommended that you enumerate the Parameters collection of the object containing the parameters you want to list.  For more information, see Examples of Converting Code to Jet Version 2.5.

Syntax

Set snapshot = querydef.ListParameters( )

The ListParameters method syntax has these 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.


See Also

Field Object, Fields Collection

ListFields Method

ListIndexes Method

QueryDef Object


ListParameters Method Applies To

QueryDef Object


CreateField Method

See Also	Example	Applies To

Creates a new Field object.

Syntax

Set variable = object.CreateField([name[, type [, size]]])

The CreateField method syntax has these parts:

Part	Description

variable	A variable declared as object data type Field.

object	The variable name of the Index, Relation, or TableDef object you want to use to create the new Field object.

name	A String variable that uniquely names the new Field object.  See the Name property for details on valid Field names.

type	An Integer constant that determines the data type of the new Field object.  See the Type property for valid data types.

size	An integer that indicates the maximum size, in bytes, of a Field object that contains text.  See the Size property for valid size values.  This argument is ignored for numeric and fixed-width fields.

Remarks

If you omit one or more of the optional parts when you use CreateField, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection.  After you append the new object, you can alter some but not all of its property settings.  See the individual property topics for more details.

Note   The type and size arguments apply only to Field objects in a TableDef object.  These arguments are ignored when a Field object is associated with Index and Relation objects.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a Field object from a collection, use the Delete method on the collection.  You can't delete a Field object from a TableDef object's Fields collection once an index has been created that references the field.


See Also

Append Method

Delete Method

Field Object, Fields Collection

Index Object, Indexes Collection

Name Property (Data Access)

Relation Object, Relations Collection

Size Property (Data Access)

TableDef Object, TableDefs Collection

Type Property


CreateField Method Applies To

Index Object

Relation Object

TableDef Object


CreateGroup Method

See Also	Example	Applies To

Creates a new Group object.

Syntax

Set variable = object.CreateGroup([name[, pid]])

The CreateGroup method syntax has these parts:

Part	Description

variable	A variable declared as object data type Group.

object	The variable name of the User or Workspace object you want to use to create the new Group object.

name	A String variable that uniquely names the new Group object.  See the Name property for details on valid Group names.

pid	A String variable containing the PID of a group account.  The identifier must contain from 4 to 20 alphanumeric characters.  See the PID property for more information on valid personal identifiers.

Remarks

If you omit one or both of the optional parts when you use CreateGroup, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection.  After you append the object, you can alter some but not all of its property settings.  See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a Group object from a collection, use the Delete method on the collection.


See Also

Append Method

Delete Method

Group Object, Groups Collection

Name Property (Data Access)

PID Property

User Object, Users Collection

Workspace Object, Workspaces Collection


CreateGroup Method Applies To

User Object

Workspace Object


CreateIndex Method

See Also	Example	Applies To

Creates a new Index object.

Syntax

Set variable = tabledef.CreateIndex([name])

The CreateIndex method syntax has these parts:

Part	Description

variable	A variable declared as object data type Index.

tabledef	The variable name of the TableDef object you want to use to create the new Index object.

name	A String variable that uniquely names the new Index object.  See the Name property for details on valid Index names.

Remarks

If you omit the optional name part when you use CreateIndex, you can use an appropriate assignment statement to set or reset the Name property before you append the new object to a collection.  After you append the object, you may or may not be able to set its Name property, depending on the type of object the Indexes collection resides in.  See the Name property topic for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove an Index object from a collection, use the Delete method on the collection.


See Also

Append Method

Delete Method

Index Object, Indexes Collection

Name Property (Data Access)

TableDef Object, TableDefs Collection


CreateIndex Method Applies To

TableDef Object


CreateProperty Method

See Also	Example	Applies To

Creates a new user-defined Property object.

Syntax

Set variable = object.CreateProperty([name[, type[, value[, fDDL]]]])

The CreateProperty method syntax has these parts:

Part	Description

variable	A variable declared as object data type Property.

object	The variable name of the Database, Field, Index, QueryDef, or TableDef object you want to use to create the new Property object.

name	A String variable that uniquely names the new Property object.  See the Name property for details on valid Property names.

type	An Integer constant that defines the data type of the new Property object.  See the Type property for valid data types.

value	A Variant variable containing the initial property value.  See the Value property for details.

fDDL	A Boolean variable indicating whether or not the Property is a DDL object.  The default is False.  If the fDDL is True, this Property object can't be changed or deleted unless the user has dbSecWriteDef permission.

Remarks

You can create a user-defined Property object only in a Properties collection of an object that is persistent (that is, already stored on disk) such as a TableDef.

If you omit one or more of the optional parts when you use CreateProperty, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection.  After you append the object, you can alter some but not all of its property settings.  See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a user-defined Property object from  the Properties collection, use the Delete method on the Properties collection.  You can't delete built-in properties.

Note   If you omit the fDDL part, it defaults to False (non-DDL).  There is no corresponding DDL property exposed, so to change a Property object from DDL to non-DDL, you must delete and re-create the Property.


See Also

Append Method

Database Object, Databases Collection

Delete Method

Field Object, Fields Collection

Index Object, Indexes Collection

Name Property (Data Access)

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection

TableDef Object, TableDefs Collection

Type Property (Data Access)

Value Property (Data Access)


CreateProperty Method Applies To

Database Object

Field Object

Index Object

QueryDef Object

TableDef Object


CreateRelation Method

See Also	Example	Applies To

Creates a new Relation object.

Syntax

Set variable = database.CreateRelation([name[, table[, foreigntable[, attributes]]]])

The CreateRelation method syntax uses these parts:

Part	Description

variable	A variable declared as object data type Relation.

database	The variable name of the Database object you want to use to create the new Relation object.

name	A String variable that uniquely names the new Relation object.  See the Name property for details on valid Relation names.

table	A String variable that names the primary table in the relation.  If the table doesn't exist before you append the Relation object, a trappable error occurs.

foreigntable	A String variable that names the foreign table in the relation.  If the table doesn't exist before you append the Relation object, a trappable error occurs.

attributes	A Long variable that contains information about the relationship type.  See the Attributes property for details.

Remarks

The Relation object relays information to the Microsoft Jet database engine about the relationship between fields in two TableDef or QueryDef objects.  The Jet engine can provide referential integrity through the Attributes property.

If you omit one or more of the optional parts when you use CreateRelation, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection.  After you append the object, none of its property settings can be altered.  See the individual property topics for more details.

Before you can use the Append method on a Relation object, you must append the appropriate Field objects to define the primary and foreign key relationship tables.

If name refers to an object that is already a member of the collection or if the Field object names provided in the subordinate Fields collection are invalid, a trappable error occurs when you use the Append method.

To remove a Relation object from a collection, use the Delete method on the collection.


See Also

Append Method

Attributes Property

Database Object, Databases Collection

Delete Method

Name Property (Data Access)

QueryDef Object, QueryDefs Collection

Relation Object, Relations Collection

TableDef Object, TableDefs Collection


CreateRelation Method Applies To

Database Object


CreateTableDef Method

See Also	Example	Applies To

Creates a new TableDef object.

Syntax

Set variable = database.CreateTableDef([name[, attributes[, source[, connect]]]])

The CreateTableDef method syntax has these parts:

Part	Description

variable	A variable declared as object data type TableDef.

database	The variable name of the Database object you want to use to create the new TableDef object.

name	A String variable that uniquely names the new TableDef object.  See the Name property for details on valid TableDef names.

attributes	A Long variable that indicates one or more characteristics of the new TableDef object.  See the Attributes property for more information.

source	A String variable containing the name of a table in an external database that is the original source of the data.  The source string becomes the SourceTableName property setting of the new TableDef object.

connect	A String variable containing information about the source of an open database, a database used in a pass-through query, or an attached table.  See the Connect property for more information on valid connect strings.

Remarks

If you omit one or more of the optional parts when you use CreateTableDef, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection.  After you append the object, you can alter some but not all of its properties.  See the individual property topics for more details.

If name refers to an object that is already a member of the collection or you specify an invalid property in the TableDef or Field object you're appending, a trappable error occurs when you use the Append method.

To remove a TableDef object from a collection, use the Delete method on the collection.


See Also

Append Method

Attributes Property

Connect Property

Database Object, Databases Collection

Delete Method

Name Property (Data Access)

TableDef Object, TableDefs Collection


CreateTableDef Method Applies To

Database Object


CreateUser Method

See Also	Example	Applies To

Creates a new User object.

Syntax

Set variable = object.CreateUser([name[, pid [, password]]])

The CreateUser method syntax has these parts:

Part	Description

variable	A variable declared as object data type User.

object	The variable name of the Group or Workspace object you want to use to create the new User object.

name	A String variable that uniquely names the new User object.  See the Name property for details on valid User names.

pid	A String variable containing the PID of a user account.  The identifier must contain from 4 to 20 alphanumeric characters.  See the PID property for more information on valid personal identifiers.

password	A String variable containing the password for the new User object.  The password can be up to 14 characters long and can include any characters except the ASCII character 0 (null).

Remarks

If you omit one or more of the optional parts when you use CreateUser, you can use an appropriate assignment statement to set or reset the corresponding property before you append the new object to a collection.  After you append the object, you can alter some but not all of its property settings.  See the individual property topics for more details.

If name refers to an object that is already a member of the collection, a trappable error occurs when you use the Append method.

To remove a User object from a collection, use the Delete method on the collection.


See Also

Append Method

Delete Method

Group Object, Groups Collection

Name Property (Data Access)

PID Property

User Object, Users Collection

Workspace Object, Workspaces Collection


CreateUser Method Applies To

Group Object

Workspace Object


CreateWorkspace Method

See Also	Example	Applies To

Creates a new Workspace object.

Syntax

Set variable = CreateWorkspace(name, user, password)

The CreateWorkspace method syntax has these parts:

Part	Description

variable	A variable declared as object data type Workspace.

name	A String variable that uniquely names the new Workspace object.  See the Name property for details on valid Workspace names.

user	A String variable that identifies the owner of the new Workspace object.  See the UserName property for more information.

password	A String variable containing the password for the new Workspace object.  The password can be up to 14 characters long and can include any characters except ASCII character 0 (null).

Remarks

Unlike the other methods you use to create data access objects, CreateWorkspace requires that you provide all of its parts.  In addition, Workspace objects aren't permanent and can't be saved.  Once you create a Workspace object, you can't alter any of its property settings.

You don't have to append the new Workspace object to a collection before you can use it.  You append a newly created Workspace object only if you need to be able to refer to it through the Workspaces collection.

If name refers to an object that is already a member of the Workspaces collection, a trappable error occurs.

Once you use CreateWorkspace to create a new Workspace object, a Workspace session is started, and you can refer to the Workspace object in your application.

To remove a Workspace object from the Workspaces collection, use the Close method on the Workspace object.

Security Note   Because all DBEngine calls within the same process space share the same Jet database engine, there exists a possible security risk if a trojan horse in-process OLE server or other DLL were to surreptitiously iterate through the DBEngine.Workspaces collection to find the Workspace used by your application, then loop through the Databases, Recordsets, Tables, and Fields collections to access your data, bypassing security and password protection.  To prevent this possibility, create a Workspace object for your application, but do not append it to the Workspaces collection.  It will then be invisible to any other code.


See Also

Append Method

Close Method

DBEngine Object

DefaultUser, DefaultPassword Properties

Delete Method

Name Property (Data Access)

UserName Property

Workspace Object, Workspaces Collection


CreateWorkspace Method Applies To

DBEngine Object


OpenRecordset Method

See Also	Example	Applies To

Creates a new Recordset object and appends it to the Recordsets collection.

Syntax

Set variable = database.OpenRecordset(source[, type[, options]])

Set variable = object.OpenRecordset([type[, options]])

The OpenRecordset method syntax has these parts:

Part	Description

variable	A variable that has been declared as object data type Recordset.

database	The name of an existing Database object you want to use to create the new Recordset.

object	The name of an existing QueryDef, Recordset, or TableDef object you want to use to create the new Recordset.  This argument can't be the name of a forward-only scrolling snapshot.
If object refers to a dynaset or snapshot-type Recordset object, the type of the new object is the same as that of the Recordset specified by object.  If object refers to a table-type Recordset object, the type of the new object is a dynaset-type Recordset.

source	A String specifying the source of the records for the new Recordset.  The source can be a table name, a query name, or an SQL statement that returns records.  For table-type Recordset objects, the source can only be a table name.

type	If you don't specify a type, OpenRecordset creates a table-type Recordset if possible.  If you specify an attached table or query, OpenRecordset creates a dynaset-type Recordset.  One of the following Integer constants that defines the data type of the new Recordset object:

  dbOpenTable [image] to open a table-type Recordset object.

  dbOpenDynaset [image] to open a dynaset-type Recordset object.

  dbOpenSnapshot [image] to open a snapshot-type Recordset object.

options	Any combination (or none) of the following Integer constants specifying characteristics of the new Recordset, such as restrictions on other users' ability to edit and view it:

  dbDenyWrite [image] Other users can't modify or add records.

  dbDenyRead [image] Other users can't view records (table-type Recordset only).

  dbReadOnly [image] You can only view records; other users can modify them.

  dbAppendOnly [image] You can only append new records (dynaset-type Recordset only).

  dbInconsistent [image] Inconsistent updates are allowed (dynaset-type Recordset only).

  dbConsistent [image] Only consistent updates are allowed (dynaset-type Recordset only).

  dbForwardOnly [image] The Recordset is a forward-only scrolling snapshot. Note that Recordset objects created with this option cannot be cloned and only support the MoveNext method to move through the records.

  dbSQLPassThrough [image] The Microsoft Jet database engine query processor is bypassed.  The query specified in the OpenRecordset source argument is passed to an ODBC backend server for processing.

  dbSeeChanges [image] Generate a run-time error if another user is changing data you are editing.

Note   The constants dbConsistent and dbInconsistent are mutually exclusive.  You can use one or the other, but not both in a given instance of OpenRecordset.

Remarks

If object refers to a QueryDef, or a dynaset- or snapshot-type Recordset, or if source refers to an SQL statement or a TableDef that represents an attached table, you can't use dbOpenTable for the type argument; if you do, a trappable error occurs.

In situations where you must use SQL syntax that is only supported by a specific ODBC server, you must use the SQL PassThrough (dbSQLPassThrough) option with the OpenRecordset method.  When using this option, the Jet query processor is bypassed and the SQL statement is transmitted to the remote ODBC database server without first performing any syntax checking or other processing. If there is a problem with the syntax or other aspects of the SQL statement, your application will trigger one or more ODBC errors. If you use SQL PassThrough, you will only be able to create snapshot-type Recordset objects -- and you must specify this type of recordset object in your code.

To perform an SQL pass-through query on a table attached to your .MDB file, you must first set the Connect property of the attached table's database to a valid ODBC connect string. For more information on this, search for Connect in the Help file.

Use the dbSeeChanges flag if you wish to trap changes made by another user or another program on your machine when you're editing or deleting the same record.  For example, if two users start editing the same record, the first user to execute the Update method succeeds.  When the Update method is executed by the second user, a run-time error occurs.  Similarly, if the second user tries to use the Delete method to delete the record, and it has already been changed by the first user, a run-time error also occurs.

Typically, if the user gets this error while updating, your code should refresh the contents of the fields and retrieve the newly modified values.  If the error occurs in the process of deleting, your code could display the new record data to the user and a message indicating that the data has recently changed.  At this point, your code can request a confirmation that the user still wants to delete the record.

Tip   Use the forward-only scrolling option (dbForwardOnly) to improve performance when your application makes a single pass through a Recordset opened from an ODBC data source.

When you close a Recordset using the Close method, it's automatically deleted from the Recordsets collection.

Note   Dynaset-, snapshot-, and table-type Recordset objects are different from the outdated Dynaset, Snapshot, and Table objects implemented in the Jet database engine versions 1.0 and 1.1.  Although they have many similar properties and methods, you can't use them interchangeably.  Several Jet engine version 3.0 methods and properties aren't applicable to these outdated data access objects.

It's recommended that you recode your applications to use the newer, more efficient Recordset object as implemented in the Jet engine versions2.5 and 3.0.


See Also

Connect Property

Database Object, Databases Collection

Dynaset Object

QueryDef Object, QueryDefs Collection

Populating Recordsets

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

TableDef Object, TableDefs Collection

Type Property


OpenRecordset Method Applies To

Database Object

QueryDef Object

Recordset Object

TableDef Object


Requery Method

See Also	Example	Applies To

Updates the data in a Recordset object by re-executing the query on which the object is based.

Syntax

recordset.Requery [newQueryDef]

The Requery method syntax has these parts:

Part	Description

recordset	A variable that has been declared as object data type Recordset.

newQueryDef	A variable that has been declared as object data type QueryDef.

Remarks

Use this method to ensure that a Recordset contains the most recent data.  When you use Requery, all changes made to the data in the underlying table by other users are displayed in the Recordset, and the first record in the Recordset becomes the current record.

You can't use the Requery method on dynaset- or snapshot-type Recordset objects whose Restartable property is set to False, nor can you use it on a table-type Recordset.

If both the BOF and EOF property settings of the Recordset object are True after you use the Requery method, the query didn't return any records and the Recordset will contain no data.

The Requery method repopulates the current Recordset by either using the current query parameters or the new ones supplied by the newQueryDef argument.  It uses the following syntax:

If the original QueryDef is supplied, then the Recordset is requeried using the parameters originally specified by the QueryDef (for instance, myquerydef.OpenRecordset()).  If a QueryDef was not used to create the Recordset, or if a different QueryDef is specified from what was originally used to create the Recordset, then the Recordset is essentially created from scratch.  Note that the Restartable property can be used to determine whether this query can be rerun, and Requery can also be used in conjunction with the CopyQuerydef method.

The following code demonstrates how you could use the Requery method:

myqudef!param1 = "cat"	' Setting parameters for the initial query.

set myrs = myqdef.OpenRecordset()	...

myqdef!param1 = "dog"	' Setting parameters for the next query.

myrs.Requery myqdef	' Setting parameters to rerun the query.


 See Also

BOF, EOF Properties

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Restartable Property


Requery Method Applies To

Recordset Object (dynaset- and snapshot-type only)


Move Method (Data Access)

See Also	Example	Applies To

Moves the position of the current record in a Recordset object.

Syntax

recordset.Move rows[, start]

The Move method syntax has these parts:

Part	Description

recordset	The name of the Recordset object whose current record position is being moved.

rows	A signed Long value specifying the number of rows the position will move.  If rows is greater than 0, the position is moved forward (toward the end of the file).  If rows is less than 0, the position is moved backward (toward the beginning of the file).

start	A String value identifying a bookmark.  If start is specified, the move begins relative to this bookmark.  If start is not specified, Move begins from the current record.

Remarks

If using Move would move the position of the current record to a position before the first record, the position is moved to the beginning-of-file (BOF) position.  If the Recordset contains no records and its BOF property is set to True, using this method to move backward produces a trappable run-time error.  If either the BOF or EOF property is True and you attempt to use the Move method without a valid bookmark, a trappable error is triggered.

If using Move would move the position of the current record to a position after the last record, the position is moved to the end-of-file (EOF) position.  If the Recordset is based on a query, then this approach forces the query to be run on the specified number of rows.  If the Recordset contains no records and its EOF property is set to True, then using this method to move forward produces a trappable run-time error.

Notes

When you use Move on a forward-only scrolling snapshot, the rows argument must be a positive integer and bookmarks aren't allowed, so you can move forward only.

To make the first, last, next, or previous record in a Recordset the current record, use the MoveFirst, MoveLast, MoveNext, or MovePrevious method.


See Also

BOF, EOF Properties

Bookmark Property

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection


Move Method Applies To

Recordset Object


FillCache Method

See Also	Example	Applies To

Fills all or a part of a local cache for a Recordset object that contains data from an ODBC data source.

Syntax

recordset.FillCache [rows[, start]]

The FillCache method syntax has these parts:

Part	Description

recordset	A Recordset object created from an ODBC data source, such as a TableDef representing an attached table or a QueryDef object derived from such a TableDef.

rows	An Integer specifying the number of rows to fill in the cache.  If you omit this argument, the value is determined by the CacheSize property setting.

start	A string specifying a bookmark.  The cache is filled starting from the record indicated by this bookmark.  If you omit this argument, the cache is filled starting from the record indicated by the CacheStart property.

Remarks

Caching improves the performance of an application that retrieves, or fetches, data from a remote server.  A cache is space in local memory that holds the data most recently fetched from the server on the assumption that the data will probably be requested again while the application is running.  When data is requested, the Microsoft Jet database engine checks the cache for the data first rather than fetching it from the server, which takes more time.  Data that doesn't come from an ODBC data source isn't saved in the cache.

Rather than waiting for the cache to be filled with records as they are fetched, you can explicitly fill the cache at any time using the FillCache method.  This is a faster way to fill the cache because FillCache fetches several records at once instead of one at a time.  For example, while each screenful of records is being displayed, you can have your application use FillCache to fetch the next screenful of records.

Any ODBC database accessed with Recordset objects can have a local cache.  To create the cache, open a Recordset object from the remote data source, and then set the CacheSize and CacheStart properties of the Recordset.

If rows and start create a range of records that is partly or wholly outside the range of records specified by the CacheSize and CacheStart properties, the portion of the recordset outside this range is ignored and isn't loaded into the cache.

If FillCache requests more records than remain in the remote data source, only the remaining records are fetched, and no error occurs.

Notes

 	Records fetched from the cache don't reflect changes made concurrently to the source data by other users.

FillCache fetches only records not already cached.  To force an update of all the cached data, set the CacheSize property of the Recordset to 0, set it to the size of the cache you originally requested, and then use FillCache.


See Also

Bookmark Property

Bookmarkable Property

CacheSize, CacheStart Properties

Database Object, Databases Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

TableDef Object, TableDefs Collection


FillCache Method Applies To

Recordset Object (dynaset-type only)


NewPassword Method

See Also	Example	Applies To

Changes the password of an existing user account.

Syntax

userobject.NewPassword oldpassword, newpassword

The NewPassword method syntax has these parts:

Part	Description

userobject	A variable of an object data type that represents the User object whose Password property you want to change.

oldpassword	A string expression that is the current setting of the Password property of the User object.

newpassword	A string expression that is the new setting of the Password property of the User object.

Remarks

If userobject doesn't refer to an existing User object (an element of a Users collection), an error occurs.  To set a new password, you must either be logged on as the user whose user account you're changing, or you must be a member of the Admins group.

The oldpassword and newpassword strings can be up to 14 characters long and can include any characters except the ASCII character 0 (null).  To clear the password, use a zero-length string ("") for newpassword.

Passwords are case-sensitive.

The Password property of a User object is write-only [image] users can't read the current value.


See Also

CreateWorkspace Method

DefaultUser, DefaultPassword Properties

Group Object, Groups Collection

Name Property (Data Access)

PID Property

User Object, Users Collection


NewPassword Method Applies To

User Object


Idle Method

See Also	Applies To

Suspends data processing, enabling the Microsoft Jet database engine to complete any pending tasks such as memory optimization or page timeouts.

Syntax

DBEngine.Idle [dbFreeLocks]

Remarks

You use the Idle method to provide the database engine with the opportunity to perform background tasks that may not be up-to-date because of intense data processing.  This is often true in multiuser, multitasking environments in which there isn't enough background processing time to keep all records in a recordset current.

Usually, read locks are removed and data in local dynaset-type Recordset objects is updated only when no other actions (including mouse movements) are occurring.  If you periodically use the Idle method, you provide the database engine with time to catch up on background processing tasks by releasing unneeded read locks.  If you specify the dbFreeLocks constant as an argument, processing is delayed until all read locks are released.

This method isn't needed in single-user environments unless multiple instances of an application are running.  The Idle method may increase performance in a multiuser environment because it forces the database engine to flush data to disk, releasing locks on memory.

You can also release read locks by making operations part of a transaction.  For example:

.

.

.

MyWorkspace.BeginTrans

Set MyRs = MyDb.OpenRecordset("MyTable")

MyWorkspace.CommitTrans

Do Until MyRs.EOF

.

.

.

MyRs.MoveNext

Loop


See Also

DBEngine Object

Recordset Object, Recordsets Collection


Idle Method Applies To

DBEngine Object


CompactDatabase Method

See Also	Example	Applies To

Copies, compacts, and gives you the option of changing the version, collating order, and encryption of a closed database.

Syntax

DBEngine.CompactDatabase olddatabase, newdatabase [, locale [, options]]

The CompactDatabase method syntax has these parts:

Part	Description

olddatabase	A string expression that is the name of an existing, closed database.  It can be a full path and filename, such as "C:\MYDB.MDB".  If the filename has an extension, you must specify it.  If your network supports it, you can also specify a network path, such as "\\MYSERVER\MYSHARE\MYDIR\MYDB.MDB".

newdatabase	A string expression that is the full path of the compacted database that you're creating.  You can also specify a network path as with olddatabase.  You can't use the newdatabase argument to specify the same database file as olddatabase.

locale	A string expression used to specify collating order for creating newdatabase, as specified in Settings.  If you omit this argument, the locale of newdatabase is the same as olddatabase.

options	An integer that indicates one or more options, as specified in Settings.  You can combine options by summing the corresponding constants.

Settings

You can use one of the following constants for the locale argument to specify the CollatingOrder property of text for string comparisons:

Constant	Collating order

dbLangGeneral	English, German, French, Portuguese, Italian, and Modern Spanish

dbLangArabic	Arabic

dbLangCzech	Czech

dbLangCyrillic	Russian

dbLangDutch	Dutch

dbLangGreek	Greek

dbLangHebrew	Hebrew

dbLangHungarian	Hungarian

dbLangIcelandic	Icelandic

dbLangNordic	Nordic languages (Microsoft Jet database engine version 1.0 only)

dbLangNorwdan	Norwegian and Danish

dbLangPolish	Polish

dbLangSwedfin	Swedish and Finnish

dbLangSpanish	Traditional Spanish

dbLangTurkish	Turkish

You can use one of the following constants in the options argument to specify whether to encrypt or to decrypt the database as it's compacted:

Constant	Description

dbEncrypt	Encrypt the database while compacting.

dbDecrypt	Decrypt the database while compacting.

If you omit an encryption constant or if you include both dbDecrypt and dbEncrypt, newdatabase will have the same encryption as olddatabase.

You can use one of the following constants in the options argument to specify the version of the data format for the compacted database.  This constant affects only the version of the data format of newdatabase and doesn't affect the version of any Microsoft Access [image] defined objects, such as forms and reports.

Constant	Description

dbVersion10	Create a database that uses the Microsoft Jet database engine version 1.0 while compacting.

dbVersion11	Create a database that uses the Microsoft Jet database engine version 1.1 while compacting.

dbVersion25	Create a database that uses the Microsoft Jet database engine version 2.5 while compacting.

dbVersion30	Create a database that uses the Microsoft Jet database engine version 3.0 while compacting.

You can specify only one version constant.  If you omit a version constant, newdatabase will have the same version as olddatabase.  You can compact newdatabase only to a version that is the same or later than that of olddatabase.

Remarks

As you change data in a database, the database file can become fragmented and use more disk space than necessary.  Periodically, you can compact your database to defragment the database file.  The compacted database is usually smaller.  You can also choose to change the collating order, the encryption, or the version of the data format while you copy and compact the database.

Warning   The CompactDatabase method won't completely convert a Microsoft Access database from one version to another.  Only the data format is converted.  Microsoft Access [image] defined objects, such as forms and reports, aren't converted.

Use the Convert Database command on the File menu of the Microsoft Access startup window to convert Microsoft Access databases from an earlier version to the current version.

The CompactDatabase method copies all the data and the security permissions settings from the database specified by olddatabase to the database specified by newdatabase.  In the process, the data in the compacted database is organized contiguously to recover disk space.

You must close olddatabase before you compact it.  In a multiuser environment, other users can't have olddatabase open while you're compacting it.  If olddatabase isn't closed or isn't available for exclusive use, an error occurs.

Because CompactDatabase creates a copy of the database, you must have enough disk space for both the original and the duplicate databases.  The compact operation fails if there isn't enough disk space available.  The newdatabase duplicate database doesn't have to be on the same disk as olddatabase.  After successfully compacting a database, you can delete the olddatabase file and rename the compacted newdatabase file to the original filename.

Note   If you use CompactDatabase to convert your current Microsoft Jet database engine version 1.1 or version 1.0 database to Jet engine version 2.5 or version 3.0 format, only applications using the compatibility mapping layer can access it.  Older applications designed to work with the Jet engine versions 1.0 and 1.1 can be adapted  to access version 2.5/3.0 databases, but this adaptation isn't performed automatically.

See Examples of Converting Code to Jet Version 2.5/3.0.


See Also

CollatingOrder Property

CreateDatabase Method

Database Object, Databases Collection

DBEngine Object


CompactDatabase Method Applies To

DBEngine Object


CreateDatabase Method

See Also	Example	Applies To

Creates a new Database object, saves the database on disk and returns an opened Database object.

Syntax

Set database = workspace.CreateDatabase (databasename, locale [, options])

The CreateDatabase method syntax has these parts:

Part	Description

database	A variable of an object data type that represents the Database object you're creating.

workspace	A variable of an object data type that represents the existing Workspace object that will contain the database.  If you omit the workspace part, the default Workspace is used.

databasename	A string expression that is the name of the database file that you're creating.  It can be the full path and filename, such as "C:\MYDB.MDB".  If you don't supply a filename extension, .MDB is appended.  If your network supports it, you can also specify a network path, such as  "\\MYSERVER\MYSHARE\MYDIR\MYDB".  Only .MDB database files can be created using this method.

locale	A string expression used to specify collating order for creating the database.  You must supply this argument or an error will occur.  See the table that lists locale constants later in this topic.

options	An integer that indicates one or more options, as specified in Settings.  You can combine options by summing the corresponding constants.

Note   The outdated CreateDatabase statement is used as a CreateDatabase method on the Workspaces(0) [image] the default Workspace.  Its use is discouraged.

Settings

You can use one of the following constants for the locale argument to specify the CollatingOrder property of text for string comparisons:

Constant	Collating order

dbLangGeneral	English, German, French, Portuguese, Italian, and Modern Spanish

dbLangArabic	Arabic

dbLangCzech	Czech

dbLangCyrillic	Russian

dbLangDutch	Dutch

dbLangGreek	Greek

dbLangHebrew	Hebrew

dbLangHungarian	Hungarian

dbLangIcelandic	Icelandic

dbLangNordic	Nordic languages (Microsoft Jet database engine version 1.0 only)

dbLangNorwdan	Norwegian and Danish

dbLangPolish	Polish

dbLangSwedfin	Swedish and Finnish

dbLangSpanish	Traditional Spanish

dbLangTurkish	Turkish

You can use one or more of the following constants in the options argument to specify which version the data format should have and whether or not to encrypt the database:

Constant	Description

dbEncrypt	Create an encrypted database.

dbVersion10	Create a database that uses the Microsoft Jet database engine version 1.0.

dbVersion11	Create a database that uses the Microsoft Jet database engine version 1.1.

dbVersion25	Create a database that uses the Microsoft Jet database engine version 2.5.

dbVersion30	Create a database that uses the Microsoft Jet database engine version 3.0.

If you omit the encryption constant, an unencrypted database is created.  You can specify only one version constant.  If you omit a version constant, a database that uses the Microsoft Jet database engine version 2.5 (for 16-bit) or 3.0 (for 32-bit) is created, depending on which environment you're working in.

Remarks

Use the CreateDatabase method to create a template for a new database the accesses the Jet engine.  The CreateDatabase method opens this new database and returns the Database object.  You must complete its structure and content using additional data access objects.  If you want to make a partial or complete copy of an existing database, you can use the CompactDatabase method to make a copy that you can customize.


See Also

CollatingOrder Property

CompactDatabase Method

Database Object, Databases Collection

DBEngine Object

OpenDatabase Method

Workspace Object, Workspaces Collection


CreateDatabase Method Applies To

Workspace Object


RegisterDatabase Method

See Also	Example	Applies To

Enters connection information for an ODBC data source in the ODBC.INI file.  The ODBC driver needs connection information when the Microsoft Jet database engine opens the data source during a session.

Syntax

DBEngine.RegisterDatabase dbname, driver, silent, attributes

The RegisterDatabase method syntax has these parts:

Part	Description

dbname	A string expression that is the name used in the OpenDatabase method that refers to a block of descriptive information about the data source.  For example, if the data source is an ODBC remote database, it could be the name of the server.

driver	A string expression that is the name of the ODBC driver.  This isn't the name of the ODBC driver dynamic link library (DLL) file.  For example, SQL Server is a driver name, 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 don't want to display the ODBC driver dialog boxes that prompt for driver-specific information or False if you do want to display the ODBC driver dialog boxes.  If silent is True, attributes must contain all the necessary driver-specific information or the dialog boxes are displayed anyway.

attributes	A 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.

Remarks

If the database is already registered (connection information is already entered) in the ODBC.INI file when you use the RegisterDatabase method, the connection information is updated.

In 32 bit installations, most of the ODBC registration information is maintained in the Windows registration database and not in the ODBC.INI file.

If the RegisterDatabase method 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, see the Help file provided with the driver.

You are encouraged to use the Windows Control Panel ODBC setup icon to add new data sources, or to make changes to existing entries.  However, if you choose to use the RegisterDatabase method, you are encouraged to set the silent option to True.


See Also

Database Object, Databases Collection

DBEngine Object

OpenDatabase Method


RegisterDatabase Method Applies To

DBEngine Object


RepairDatabase Method

See Also	Example	Applies To

Attempts to repair a corrupted database that accesses the Microsoft Jet database engine.

Syntax

DBEngine.RepairDatabase dbname

The dbname placeholder represents a string expression that is the path and filename for an existing Jet engine database file.  If you omit the path, only the current directory is searched.  If your system supports the uniform naming convention (UNC), you can also specify a network path, such as: "\\MYSERVER\MYSHARE\MYDIR\MYDB.MDB".

Remarks

You must close the database specified by dbname before you repair it.  In a multiuser environment, other users can't have dbname open while you're repairing it.  If dbname isn't closed or isn't available for exclusive use, an error occurs.

This method attempts to repair a database that was marked as possibly corrupt by an incomplete write operation.  This can occur if an application using the Jet engine is closed unexpectedly because of a power outage or computer hardware problem.  The database won't be marked as possibly corrupt if you use the Close method or if you quit your application in a usual way.

The RepairDatabase method also attempts to validate all system tables and all indexes.  Any data that can't be repaired is discarded.  If the database can't be repaired, a trappable error occurs.

When you attempt to open or compact a corrupted database, a trappable error usually occurs.  In some situations, however, a corrupted database may not be detected, and no error occurs.  It's a good idea to provide your users with a way to use the RepairDatabase method in your application if their database behaves unpredictably.

Some types of databases can become corrupted if a user ends an application without closing Database or Recordset objects and the Jet engine; Microsoft Windows or MS-DOS doesn't have a chance to flush data caches.  To avoid corrupt databases, establish procedures for closing applications and shutting down systems that ensure that all cached pages are saved to the database.  In some cases, power supplies that can't be interrupted may be necessary to prevent accidental data loss during power fluctuations.

Tip   After repairing a database, it's also a good idea to compact it using the CompactDatabase method to defragment the file and to recover disk space.


See Also

Close Method

CompactDatabase Method

Database Object, Databases Collection

DBEngine Object


RepairDatabase Method Applies To

DBEngine Object


OpenDatabase Method

See Also	Example	Applies To

Opens a specified database in a session and returns a reference to the Database object that represents it.  The open database is automatically added to the Databases collection.

Syntax

Set database = workspace.OpenDatabase(dbname[, exclusive[, read-only[, source]]])

The OpenDatabase method syntax has these parts:

Part	Description

database	A variable of a Database object data type that represents the Database object that you're opening.

workspace	A variable of a Workspace object data type that represents the existing Workspace object that will contain the database.

dbname	A string expression that is the name of an existing database file or registered ODBC data source name.  If the filename has an extension, it's required.  If your network supports it, you can also specify a network path, such as "\\MYSERVER\MYSHARE\MYDIR\MYDB.MDB".

Some considerations apply when using dbname:

  If it refers to a database that is already open for exclusive access by another user, an error occurs.

  If it doesn't refer to an existing database or valid ODBC data source name, an error occurs.

  If it's a zero-length string ("") and source is "ODBC;", a dialog box listing all registered ODBC data source names is displayed so the user can select a database.

exclusive	A Boolean value that is True if the database is to be opened for exclusive (nonshared) access and False if the database is to be opened for shared access.  If you omit this argument, the database is opened for shared access.

read-only	A Boolean value that is True if the database is to be opened for read-only access and False if the database is to be opened for read/write access.  If you omit this argument, the database is opened for read/write access.

source	A string expression used for opening the database.  This string constitutes the ODBC connect arguments.  You must supply the exclusive and read-only arguments to supply a source string.  See the Connect property for syntax.

Remarks

To close a database, and thus remove its Database object from the Databases collection, use the Close method on the object.

For more information about ODBC drivers, such as SQL Server, see the Help file provided with the driver.

Note   The source argument is expressed in two parts, the database type, followed by a semicolon (;) and the optional parameters.  The database type, like "ODBC;" or "FoxPro 2.5" must be provided first.  The optional arguments follow in no particular order [image] separated by semicolons.


See Also

Close Method

Connect Property

Database Object, Databases Collection

Workspace Object, Workspaces Collection


OpenDatabase Method Applies To

Workspace Object


RefreshLink Method

See Also	Example	Applies To

Updates the connection information for an attached table.

Syntax

tabledef.RefreshLink

The tabledef placeholder specifies the TableDef object representing the attached table whose connection information you want to update.

Remarks

You change the connection information for an attached table by resetting the Connect property of the corresponding TableDef object and then using the RefreshLink method to update the information.  When you use RefreshLink, the attached table's properties and Relation objects aren't changed.

To force this connection information to exist in all collections associated with the TableDef object that represents the attached table, you must also use the Refresh method on each collection.


See Also

Connect Property

Recordset Object, Recordsets Collection

Refresh Method (Data Access)

Relation Object, Relations Collection

TableDef Object, TableDefs Collection


RefreshLink Method Applies To

TableDef Object


CancelUpdate Method

See Also	Applies To

Cancels any pending updates for the Recordset object represented by the object placeholder.

Syntax

object.CancelUpdate

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The CancelUpdate method cancels any pending updates due to an Edit or AddNew operation.  For example, if a user invokes the Edit or AddNew method and hasn't yet invoked the Update method, CancelUpdate cancels any changes made after Edit or AddNew was invoked.

Note   Using the CancelUpdate method has the same effect as moving to another record without using the Update method except that the current record doesn't change, and various properties, such as BOF and EOF, aren't updated.

Use the EditMode property to determine if there is a pending operation that can be canceled.


CancelUpdate Method Applies To

Recordset Object


See Also

AddNew Method

BOF, EOF Properties

EditMode Property

Recordset Object

Update Method


CopyQueryDef Method

See Also	Applies To

Returns a QueryDef object which is a copy of the QueryDef used to create the Recordset object represented by the object placeholder.

Syntax

object.CopyQueryDef

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Creates a new QueryDef that is a duplicate of the QueryDef used to created this Recordset.  If a QueryDef wasn't used to create this Recordset, this method returns a null value.


CopyQueryDef Method Applies To

Recordset Object


See Also

QueryDef Object, QueryDef Collections


CreateQueryDef Method Example

This example creates a QueryDef named All Pubs with an SQL statement, and then creates a dynaset-type Recordset based on the query.

Dim MyDB As Database, MyQuery As QueryDef, MySet As Recordset

' Open a database.

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

' Create a QueryDef.

Set MyQuery = MyDB.CreateQueryDef("All Pubs",  _

"SELECT * FROM Publishers;")

' Create Recordset from query.

Set MySet = MyDB.OpenRecordset("All Pubs")

...

MySet.Close	' Close Recordset object.


DeleteQueryDef Method Example

This example creates and then deletes a QueryDef object.  It also uses the QueryDef to create a snapshot-type Recordset.

Dim MyDB As Database, MyQuery As QueryDef, ListSet As Recordset

' Open a database.

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

' Create the QueryDef.

Set MyQuery = MyDB.CreateQueryDef("All Pubs",  _

"SELECT * FROM Publishers;")

' Create snapshot-Recordset.

Set ListSet = MyQuery.OpenRecordset(dbOpenSnapshot)

' Delete QueryDef.

MyDB.DeleteQueryDef("All Pubs")


OpenQueryDef Method Example

This example provides a value for the State Wanted parameter of an existing query named By State and creates a snapshot-type Recordset of the records for all publishers in New York.

Dim MyDB As Database, MyQuery As QueryDef, MySet As Recordset

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set MyQuery = MyDB.OpenQueryDef![By State]	' Open QueryDef.

MyQuery.Parameters![Enter State] = "NY"	' Set parameter.

' Create snapshot-type Recordset.

Set MySet = MyQuery.OpenRecordset(dbOpenSnapshot)

...


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 Recordset

' Open a database.

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

' Open a table.

Set MyTable = MyDB.OpenRecordset("Publishers",dbopenTable)

MyTable.Index = "PrimaryKey"	' Define current index.

MyTable.Seek "=", 3	' Seek record.

If MyTable.NoMatch Then...

This example uses the OpenDatabase method to directly open an installable ISAM database and then uses Seek to locate a record in a table in that database.

Dim Db as Database

Dim Rst as Recordset, SaveHere as Variant

Set Db = OpenDatabase("C:\FoxData", False, False,"Fox 2.5")

Set Rst = OpenRecordset("PARTS.DBF", dbOpenTable)

' Choose record order and Seek index.

Rst.Index = "PartNameIndex"

Rst.Bookmark = Rst.BookMark	' Save current location.

' Search for first instance of a chosen part.

Rst.Seek = "Framis Lever"

If Rst.NoMatch then 	' Test for success.

Rst.BookMark = SaveHere	' Seek not successful.

...

Else	' Seek worked; use current record.

Debug.Print Rst!PartName

End If


Delete Method Example

This example finds a record in a  Recordset  and deletes it.

' Find the record you want to delete.

MyRecordset.FindFirst "PubNum = 9"

If Not MyRecordset.NoMatch Then	' Check if record found.

MyRecordset.Delete	' Delete the record.

End If

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

Dim MyDB As Database, MyTableDef As TableDef, MyIndex As Index

' Open the database.

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set MyTableDef = MyDB.TableDefs("Publishers")	' Set the TableDef.

Set MyIndex = MyTableDef.CreateIndex("Author Name")

Set MyField = MyIndex.CreateField("Author")

MyIndex.Fields.Append MyField	' Add Field to Index.

MyRsDef.Indexes.Append MyIndex	' Add Index to TableDef.

...

MyRsDef.Indexes.Delete "Author Name"	' Delete the Index.


OpenRecordset, Edit, Update Methods; Recordset Object, Recordsets Collection Example

This example finds the first record in a Recordset object that matches 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.

MyRecordset.FindFirst Criteria	' Make record current.

Do While Not MyRecordset.NoMatch

If Not Data1.Recordset.NoMatch Then

MyRecordset.Edit	' Open record.

MyRecordset.Fields("Title") = NewTitle	' Enter new title.

MyRecordset.Update	' Save changes.

End If

MyRecordset.FindNext Criteria

Loop

The following example achieves the same effect without using the Edit method.

' Create the criteria string.

SQLQuery = "UPDATE Titles SET Title = 'My Right Foot'"

SQLQuery = SQLQuery & " WHERE Title = 'My Right Hand';"

MyDatabase.Execute SQLQuery	' Execute the query.

This example opens a Recordset object and locates each record whose Title field satisfies the search criteria and copies it to the copy buffer.  The example then prepares the record for subsequent editing, changes the job title, and saves the change using the Update method.

Dim Criteria As String, MyDB As Database, MySet As Recordset

Dim NewTitle As String

' Set search criteria.

Criteria = "Title = 'Sales Representative'"

NewTitle = "Account Executive"	' Set new job title.

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create dynaset.

Set MySet = MyDB.OpenRecordset("Employees", dbOpenDynaset)

MySet.FindFirst Criteria	' Find first occurrence.

' Loop until no matching records.

Do Until MySet.NoMatch

MySet.Edit	' Enable editing.

MySet!Title = NewTitle	' Change title.

MySet.Update	' Save changes.

MySet.FindNext Criteria	' Find next occurrence.

Loop	' End of loop.

Tip   Using an update query to change job titles might be more efficient.  For example you could use the following code to achieve the same results:

SQL$ = "Update Employees Set Title = 'Account Executive' " "

& " "WHERE Title = 'Sales Representative' "

MyDb.Execute SQL$


FindFirst, FindLast, FindNext, FindPrevious Methods Example

This example uses FindFirst to find the first record matching the specified criteria in a Recordset object and then uses FindNext to find the next matching record.

Dim MyCriteria As String

MyCriteria = "State = 'NY'"	' Set the criteria.

My.Recordset.FindFirst MyCriteria	' Find first matching record.

If Not My.Recordset.NoMatch Then...	' Check if record is found.

...

My.Recordset.FindNext MyCriteria	' Find next matching record.

This example creates a dynaset-type Recordset object and then uses FindFirst to locate the first record satisfying the title condition.

Dim MyCriteria As String, MyDB As Database, MySet As Recordset

MyCriteria = "State = 'NY'" 	' Define search criteria.

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")

' Create a dynaset-type Recordset based on Publishers table.

Set MySet = MyDB.OpenRecordset("Publishers",dbOpenDynaset)

MySet.FindFirst MyCriteria	' Find first matching record.

If MySet.NoMatch Then...	' Check if record is found.

...

MySet.FindNext MyCriteria	' Find next matching record.


Update Method Example

This example changes the Title field in the current record of a Recordset object and then uses the Update method to save the changes.

My.Recordset.Edit	' Enable editing.

My.Recordset.Fields("Title") = "My Right Foot"	' Change title.

My.Recordset.Update	' Save changes.


Append Method Example

The example defines a new field and appends it to a Fields collection.

Dim MyDB As Database, Fd As Field

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")  ' Open a database.

Fd.Name = "Phone"	' Set field properties.

Fd.Type = dbText

Fd.Size = 15

MyDB.TableDefs("Authors").Fields.Append Fd	' Add field to collection.


CompactDatabase Method Example

This example uses CompactDatabase to compact a database called 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.

DBEngine.CompactDatabase "C:\PUBS.MDB","C:\PUBSNEW.MDB","",dbEncrypt

...

Kill "C:\PUBS.BAK"

Name "C:\PUBS.MDB" As "C:\PUBS.BAK"

Name "C:\PUBSNEW.MDB" As "C:\PUBS.MDB"

This example copies a database named MYDB.MDB and keeps a new, compacted copy named MYDB.NEW.  The new database has the same collating order as the original database, but it's encrypted.

DBEngine.CompactDatabase "C:\MYDB.MDB", "C:\MYDB.NEW", dbLangGeneral, _

dbEncrypt


CreateDatabase Method Example

This example uses CreateDatabase to create a new, encrypted Database object named CurrentDatabase.  The example customizes some properties of the new database, completes its structure, and then closes it.

Dim DefaultWorkspace As Workspace

Dim CurrentDatabase As Database, MyDatabase As Database

Set DefaultWorkspace = DBEngine.Workspaces(0)

Set CurrentDatabase = DefaultWorkspace.Databases(0)

' Create new, encrypted database.

Set MyDatabase = DefaultWorkspace.CreateDatabase ("NEWDB.MDB", _

dbLangGeneral, dbEncrypt)

' Fill in new database.

' Set property to that of current database.

MyDatabase.QueryTimeout = CurrentDatabase.QueryTimeout

...

' Complete structure of MyDatabase, possibly using structure of

' CurrentDatabase.

...

MyDatabase.Close


CreateDynaset Method Example

This example uses an SQL statement to create a read-only Dynaset object of Publishers from New York.

Dim MyDB As Database, MySet As Dynaset, MyRset as Recordset

Dim MyTable As Table, SQLStmt As String

Const dbReadOnly = 4	' Set constant.

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")	' Open database.

' Set text for the SQL statement.

SQLStmt = "SELECT * FROM Publishers WHERE State = 'NY'"

' Create the new Dynaset.

It's recommended that you convert your code to use the new dynaset-type Recordset object instead of the outdated Dynaset object.  This example creates a dynaset-type Recordset.

Set MySet = MyDB.CreateDynaset(SQLStmt, dbReadOnly )

Set MyRset = MyDB.OpenRecordset(SQLStmt, dbOpenDynaset, dbReadOnly )


CreateSnapshot Method Example

The first part of this example creates a Snapshot object of publishers located in California and sorted by zip code.  The second part recreates the Snapshot with a new sort order.

Dim MyDB As Database, MySet As Snapshot

Dim MyRset as Recordset, MySQL As String

Set MyDB = Workspaces(0).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()

It's recommended that you convert your code to use the new snapshot-type Recordset object instead of the outdated Snapshot object.  This example creates a snapshot-type Recordset.

Set MyRset = MyDB.OpenRecordset(SQLStmt, dbOpenSnapshot)

...

MyRset.Sort = "Publisher's Name"

Set MyRset = MyRSet.OpenRecordset(dbOpenSnapshot)


Execute Method Example

This example uses a Data control to execute an action query that updates all titles that have no value in the ISBN column in the Titles table.  If there is an error, all changes are rolled back.

Dim SQL as String

SQL = "DELETE FROM Titles WHERE ISBN IS NULL"

My.Database.Execute SQL, dbFailOnError


ExecuteSQL Method Example

This example uses ExecuteSQL to execute an action query that changes City from New York to NY in the ODBC-accessed Publishers table.

MySQL = "UPDATE Publishers SET City = 'NY' WHERE City = 'New York'"

RecsChanged = MyOracleDB.ExecuteSQL MySQL


OpenTable Method Example

This example uses OpenTable to open the Publishers table in the BIBLIO.MDB database.

Dim MyDB As Database, MyTable As Table

Set MyDB = Workspaces(0).OpenDatabase("BIBLIO.MDB")	' Open Database.

Set MyTable = MyDB.OpenTable("Publishers")	' Open Table.

...

MyTable.Close	' Close Table.

It's recommended that you convert your code to use the new table-type Recordset object instead of the outdated Table object.  This example creates a table-type Recordset.

Dim MyDB As Database, MyRSTable As Recordset

' Open table-type Recordset .

Set MyRSTable = MyDB.OpenRecordset("Publishers", dbOpenTable)

...

MyRSTable.Close	' Close Recordset.


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 object 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


Clone Method Example

This example creates a Recordset object using an SQL query and then uses Clone to create a clone of the Recordset so that bookmarks can be shared between the two objects.  This technique is especially useful when you have to compare the results of a query from more than one point at the same time.  The example creates two sorted lists of the same data: One sorted by Author and the other by Title.  Selections from either list can be used to fetch records based on either Recordset because they share the same bookmarks.

Dim Db as Database

Dim Rs1 as Recordset, Rs2 as Recordset

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set Rs1 = Db.OpenRecordset("SELECT * FROM Titles " _

& " WHERE [Year Published] > 1993 ORDER by Title"

Set Rs2 = Rs1.Clone()	' Clone Recordset.

Rs2.MoveFirst	' Set current record.

Do Until Rs1.EOF

List1.AddItem Rs1!Author	' Add to self-sorting list box.

Rs1.MoveNext

Loop

Do Until Rs2.EOF

List1.AddItem Rs2!Title	' Add to list box.

Rs2.MoveNext

Loop


AddNew Method, LastModified Property Example

This example creates a new record in a table named Customers, enters values, saves the changes, and then moves to and deletes the new record.

Dim MyDb As Database, MyTable As Recordset

Set MyDb = Workspaces(0).OpenDatabase("MYDB.MDB")

' Open table.

Set MyTable = MyDB.OpenRecordset("Customers", dbOpenTable)

MyTable.AddNew	' Create new record.

MyTable("Customer ID") = "FINNF"	' Set record key.

MyTable("Company Name") = "Finnegan's Foods"	' Set company name.

MyTable.Update	' Save changes.

MyTable.Move 0, MyTable.LastModified	' Go to new record

MyTable.Delete	' Delete new record.

MyTable.Close	' Close Table.

MyDb.Close	' Close Database


MoveFirst, MoveLast, MoveNext, MovePrevious Methods Example

This example changes the job title of all sales representatives in a table named Employees.  After opening the table, it uses MoveFirst to locate the first record and MoveNext to move to the next record.  For each record satisfying the title condition, the example changes the title and saves the change using the Update method.

It's far more efficient to use the WHERE clause of an SQL statement to request the records you want to update than to test each record one at a time.  The whole operation could be accomplished by using a single UPDATE statement, as shown below.

Dim MyDB As Database, MyTable As Recordset, SQL as String

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

SQL$ = "Select * FROM Employees WHERE Title = 'Sales Representative' "

' Open recordset.

Set MyTable = MyDB.OpenRecordset(SQL$, dbOpenDynaset)

Do Until MyTable.EOF	' Begin loop.

MyTable.Edit	' Enable editing.

MyTable!Title = "Account Executive"	' Change title.

MyTable.Update	' Save changes.

MyTable.MoveNext	' Locate next record.

Loop	' End of loop.

MyTable.Close	' Close table.

MyDB.Close

Tips

Using an update query to change job titles might be more efficient.  For example, you could use the following code to achieve the same results:

Dim SQL as String

SQL$ = "Update Employees Set Title = 'Account Executive' " " _

& " "WHERE Title = 'Sales Representative' "

MyDb.Execute SQL$


Close Method Example

This example opens and then closes a database and a table-type Recordset object for the Customers table in the database.

Dim MyDatabase As Database, MyRecordset As Recordset

' Open database.

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Open table.

Set MyRecordset = MyDatabase.OpenRecordset("Customers")

...

MyRecordset.Close	' Close table.

MyDatabase.Close	' Close database.


Refresh Method (Data Access) Example
Refresh Method Example

This example refreshes the Tables collection in a database in a multiuser environment in case another user has made changes.

Dim MyWorkspace As Workspace, MyDatabase As Database

' Get default workspace.

Set MyWorkspace = Workspaces(0)

' Open database.

Set MyDatabase = MyWorkspace.OpenDatabase("MYDB.MDB")

...

' Refresh possibly changed collection.

MyDatabase.Containers("Tables").Documents.Refresh


BeginTrans, CommitTrans, Rollback Methods Example

This example changes the job title of all sales representatives in the Employees table of the database.  After the BeginTrans method starts a transaction that isolates all the changes made to the Employees table, the CommitTrans method saves the changes.  Notice that you can use the Rollback method to undo changes that you saved using the Update method.

One or more table pages remain locked while the user decides whether or not to accept the changes.  For this reason, this technique isn't recommended but only shown as an example.

Function ChangeTitle

Dim CRLF As String, EmployeeName As String

Dim Message As String, Prompt As String

Dim MyWorkspace As Workspace, MyDatabase As Database, MyTable _

As Recordset

CRLF = Chr$(13) & Chr$(10)

Prompt = "Change title to Account Executive?"

Set MyWorkspace = Workspaces(0)   ' Get default Workspace.

' Get current database.

Set MyDatabase = MyWorkspace.OpenDatabase("MYDB.MDB")

' Open table.

Set MyTable = MyDatabase.OpenRecordset("Employees", dbOpenTable)

MyWorkspace.BeginTrans	' Start of transaction.

MyTable.MoveFirst

Do Until MyTable.EOF

If MyTable![Title] = "Sales Representative" Then

EmployeeName = MyTable![Last Name] & ", " & MyTable! _

[First_Name]

Message = "Employee: " & EmployeeName & CRLF & CRLF

If MsgBox(Message & Prompt, vbQuestion + vbYesNo, "Change Job

Title") = YES Then

MyTable.Edit	' Enable editing.

MyTable![Title] = "Account Executive"   ' Change job title.

MyTable.Update	' Save changes.

End If

End If

MyTable.MoveNext	' Move to next record.

Loop

If MsgBox("Save all changes?", vbQuestion + vbYesNo, _

" Save Changes") = YES Then

MyWorkspace.CommitTrans	' Commit changes.

Else

MyWorkspace.Rollback	' Undo changes.

End If

MyTable.Close	' Close table.

MyDatabase.Close

End Function


OpenDatabase Method Example

This example opens the Employees table in the database in the default Workspace object.  If the database can't be opened (for example, if it has already been opened for exclusive access by another user in a multiuser environment), an error occurs and a message is displayed.  Then the example updates the Title field of the Employees table.

Function UpdateNorthwind () As Integer

Dim MyWorkspace As Workspace, MyDatabase As Database

Dim MyTable As Recordset

Dim MyFile As String

Dim ErrorCondition As Integer

UpdateDb = True

MyFile = "MYDB.MDB"	' Define name of database.

On Error GoTo DBErrorHandler	' Enable error trapping.

Set MyWorkspace = Workspaces(0)

' Open database.

Set MyDatabase = MyWorkspace.OpenDatabase(MyFile)

If Not ErrorCondition Then

On Error GoTo TableErrorHandler	' Enable error trapping.

' Open table.

Set MyTable = MyDatabase.OpenRecordset("Employees")

If Not ErrorCondition Then

On Error GoTo EditErrorHandler	' Enable error trapping.

Do Until MyTable.EOF

If MyTable![Title] = "Sales Representative" Then

MyTable.Edit	' Enable editing.

MyTable![Title] = "Account Executive"   ' Make changes.

MyTable.Update	' Save changes.

End If

MyTable.MoveNext	' Move to next record.

Loop

MyTable.Close	' Close table.

End If

MyDatabase.Close	' Close database.

End If

On Error GoTo 0	' Disable error trapping.

Exit Function

DBErrorHandler:

ErrorCondition = True

UpdateDb = False

MsgBox "Can't open database.", vbExclamation

Resume Next

TableErrorHandler:

ErrorCondition = True

UpdateDb = False

MsgBox "Can't open Employees table.", vbExclamation

Resume Next

EditErrorHandler:

ErrorCondition = True

UpdateDb = False

MsgBox "Can't edit Employees table.", vbExclamation

Resume Next

End Function


RegisterDatabase Method Example

This example registers a SQL Server data source named PtLudlow and then opens the database MySQLDb on that server.

Using the Windows ODBC control panel icon is the preferred way to create, modify or delete data source names.

Dim MyDatabase As Database

Dim Attribs As String

' Build keywords string.

Attribs = "Description=SQL Server on server PtLudlow" & Chr$(13)

Attribs = Attribs & "OemToAnsi=No" & Chr$(13)

Attribs = Attribs & "Network=DBNMP3" & Chr$(13)

Attribs = Attribs & "Address=\\PTLUDLOW\PIPE\SQL\QUERY" & Chr$(13)

Attribs = Attribs & "Database=MySQLDb"

' Update ODBC.INI.

DBEngine.RegisterDatabase "PtLudlow", "SQL Server", True, Attribs

...

' Open the database.

Set MyDatabase = Workspaces(0).OpenDatabase("PtLudlow", False, _

False, "ODBC;")


RepairDatabase Method Example

This example attempts to repair a database named MYDB.MDB.

DBEngine.RepairDatabase "C:\MYDB.MDB"


AppendChunk, FieldSize, Getchunk Methods Example

This example uses the GetChunk method to return consecutive 16K chunks of the Notes field in the Employees table of the database MYDB.MDB.  It uses FieldSize to determine how many chunks it needs to copy and copies the chunks to the string array NoteArray() where they can be changed.  It then uses AppendChunk to copy NoteArray() back to Notes.

' This line should be in Declarations section.

Option Base 1

Function GetNotes

Const ChunkSize = 16384	' Set size of chunk.

Dim NumChunks As Integer, TotalSize As Long, X As Integer

Dim MyDatabase As Database, MyRecordset As Recordset

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Open table.

Set MyRecordset = MyDatabase.OpenRecordset("Employees")

' Get field size.

TotalSize = MyRecordset![Notes].FieldSize()

' How many chunks?

NumChunks = TotalSize \ ChunkSize - (TotalSize Mod ChunkSize <> 0)

ReDim NoteArray(NumChunks) As String * ChunkSize

' Get current Notes field.

For X = 1 To NumChunks

NoteArray(X) = MyRecordset![Notes].GetChunk((X - 1) * _

ChunkSize, ChunkSize)

Next X

...	' Make changes.

MyRecordset.Edit	' Enable editing.

MyRecordset!Notes = ""	' Initialize Notes field.

For X = 1 To NumChunks

' Replace with edited Notes.

MyRecordset![Notes].AppendChunk NoteArray(X)

Next X

MyRecordset.Update	' Save changes.

MyRecordset.Close	' Close table.

   MyDatabase.Close 	'Close database.

End Function


Move Method Example

This example creates a function that moves the current record position in a Recordset forward or back a specified number of records and provides an optional offset.

Sub MoveRelative (Distance As Long, Direction As String, MyRecordset _

As Recordset, RelativeBookMark As String)

Dim Here As String

Here = MyRecordset.Bookmark

Direction = UCase(Direction)

Select Case Direction

Case "FWD":  Distance = Abs(Distance)

Case "BACK": Distance = Abs(Distance) * -1

Case Else: MsgBox "Incorrect calling argument"

End Select

If UCase(RelativeBookMark) = "HERE" Then

MyRecordset.Move Distance	' Move current record position.

Else

' Move relative to bookmark.

MyRecordset.Move Distance, RelativeBookMark

End If

' Move may not have been completed.

If MyRecordset.EOF Or MyRecordset.BOF Then Beep

End Sub


RefreshLink Method Example

This example attaches a Paradox table named PDX_Author to a database opened for exclusive use, moves the connection to a different directory, and then refreshes the connection information.

Dim MyDb As Database, MyTable As TableDef

' Open database.

Set MyDb = MyWorkspaces(0).OpenDatabase("C:\CONTACTS\PUBS.MDB")

Set MyTable = MyDB.CreateTableDef("PDX_Author", dbAttachExclusive)

MyTable.SourceTableName = "Author"

MyTable.Connect = "Paradox 3.x; " _

& "DATABASE = C:\PDX\PUBS; PWD=books"

' Append to TableDefs collection.

MyDB.TableDefs.Append MyTable

' Move to new directory.

MyDB.TableDefs!PDX_Author.Connect = "Paradox 3.x; " _

& "DATABASE = N:\PDX\PUBS; PWD=books"

' Refresh connection information.

MyDB.TableDefs!PDX_Author.RefreshLink


CreateField Method Example

This example creates a new Field object.

Dim MyDatabase As Database

Dim MyTableDef As TableDef

Dim MyField As Field

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTableDef = MyDatabase.TableDefs("MyTable")

' Create new Field object.

Set MyField = MyTableDef.CreateField("Phone", dbText)

' Set another property of MyField.

MyField.Size = 25	' Greater than longest phone number.

' Save Field definition by appending it to Fields collection.

MyTableDef.Fields.Append MyField


CreateGroup Method Example

This example creates a new Group object.

Dim MyGroup As Group, ManagersPID As String

ManagersPID = "2222abc"

' Create new Group object.

Set MyGroup = Workspaces(0).CreateGroup("Managers", ManagersPID)

' Create new group in workgroup by appending it to Groups collection.

DBEngine.Workspaces(0).Groups.Append MyGroup


CreateUser Method Example

This example creates a new User object.

Dim MyUser As User

Dim ManagersPID As String

ManagersPID = "1122aabb"

' Create new user account.

Set MyUser = Workspaces(0).CreateUser("Senior Partner", ManagersPID)

' Set other properties of MyUser.

MyUser.Password = "NewPassword"

' Save user account definition by appending it to Users collection.

Workspaces(0).Users.Append MyUser

' Add user to predefined Users group.

MyUser.Groups.Append MyUser.CreateGroup("Users")


CreateIndex Method Example

This example creates a new Index object.

Dim MyIndex As Index

Dim MyField As Field

Dim MyTableDef As TableDef

Dim MyDatabase As Database

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTableDef = MyDatabase.TableDefs(0)

' Create new Index object.

Set MyIndex = MyTableDef.CreateIndex("Another")

Set MyField = MyIndex.CreateField("LastName")

MyIndex.Primary = True

MyIndex.Required = True

MyIndex.Fields.Append MyField

' Save Index definition by appending it to Indexes collection.

MyTableDef.Indexes.Append MyIndex


CreateProperty Method Example

This example creates a new Property object.

Dim MyProperty As Property

Dim MyDatabase As Database

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create new Property object.

Set MyProperty = MyDatabase.CreateProperty("Privilege")

' Set other properties of MyProperty.

MyProperty.Type = dbBoolean

MyProperty.Value = True

' Save Property definition by appending it to Properties collection.

MyDatabase.Properties.Append MyProperty


CreateRelation Method Example

This example creates a new Relation object.  In this case, the Customers table is related to a ValidStates table.  Once established, the relationship requires that an entry exist in the ValidStates table corresponding to the Customers.CustState field before it can be added to the Customers table.  Any changes to the State field that violates this relationship triggers a trappable error.

By setting the dbRelationUpdateCascade attribute, the Microsoft Jet database engine changes the Primary table Customers.CustState if a corresponding value changes in the ValidStates table.  For example, if the ValidState entry TR was changed to TX, all Customers records having TR as a CustState code would be changed to TX.

Dim MyRelation As Relation

Dim MyDatabase As Database

Dim MyField As Field

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create new Relation object.

Set MyRelation = MyDatabase.CreateRelation("TableRelationOne")

MyRelation.Table = "Customers"	'Name the Primary Table.

MyRelation.ForeignTable = "ValidStates"	'Name the Foreign Table.

MyRelation.Attributes = dbRelationUpdateCascade

Set MyField = MyRelation.CreateField("CustState")

MyField.ForeignName = "StateCode"

MyRelation.Fields.Append MyField

' Save Relation definition by appending it to Relations collection.

MyDatabase.Relations.Append MyRelation


CreateTableDef Method Example

This example creates a new TableDef object in  the BIBLIO.MDB database.

Dim MyTableDef As TableDef, MyField As Field

Dim MyDatabase As Database

Set MyDatabase = Workspaces(0).OpenDatabase("BIBLIO.MDB")

' Create new TableDef.

Set MyTableDef = MyDatabase.CreateTableDef("Title Detail")

' Add field to MyTableDef.

Set MyField = MyTableDef.CreateField("Comments",dbDate)

MyTableDef.Fields.Append MyField

' Save TableDef definition by appending it to TableDefs collection.

MyDatabase.TableDefs.Append MyTableDef


CreateWorkspace Method Example

This example creates a new Workspace object named Special, sets its UserName property to the UserName property setting of the default workspace, and sets the workspaces security context to MyUserName, which means that you must supply MyUserNames password.

Dim MyWorkspace As Workspace

Dim MyUserName As String

' Get UserName of default workspace.

MyUserName = DBEngine.Workspaces(0).UserName

' NOTE: Insert the path to your .INI file in this line.

DBEngine.IniPath = "C:\MYAPPDIR\MYAPP.INI"

' Create new workspace.

Set MyWorkspace = DBEngine.CreateWorkspace("Special", MyUserName, _

"SpecialPW")


CacheSize, CacheStart Properties, FillCache Method Example

This example opens a Recordset from an Order Detail table stored on an ODBC server, sets the CacheSize and CacheStart properties, and then uses FillCache to cache data from the server to the database.

Dim MyRecordset As Recordset, MyDatabase As Database

' Open database containing attached ODBC table.

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Open local recordset.

Set MyRecordset = MyDatabase.OpenRecordset("OrderDetail",DbOpenDynaset)

' Locate record whose Customer ID is 1001.

MyRecordset.FindFirst "CustID = 1001"

' Start caching records at Customer ID 1001.

MyRecordset.CacheStart = MyRecordset.Bookmark

MyRecordset.CacheSize = 12	' Set cache size to 12 records.

MyRecordset.FillCache	' Fill cache.

...	' Display rows.


NewPassword Method Example

This example changes the password of the existing user Pat Smith from My Secret to msMSApw.  The user must be logged on as Pat Smith or as a member of the Admins group.

Workspaces(0).Users("Pat Smith").NewPassword "My Secret", "msMSApw"


BOF, EOF Properties

See Also	Example	Applies To

BOF [image] returns a value that indicates whether the current record position is before the first record in a Recordset.

EOF [image] returns a value that indicates whether the current record position is after the last record in a Recordset.

These properties also apply to the outdated Dynaset, Snapshot, and Table objects.

Syntax

object.BOF

object.EOF

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The BOF property return values are:

Value	Description

True	The current record position is before the first record.

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

The EOF return values are:

Value	Description

True	The current record position is after the last record.

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

Remarks

The BOF and EOF return values are determined by the location of the current record pointer.

You can use the BOF and EOF properties to determine whether a Recordset object contains records or whether you've gone beyond the limits of a Recordset as you move from record to record.

If either BOF or EOF is True, there is no current record.

If you open a Recordset containing no records, BOF and EOF are set to True, and the recordset's RecordCount property setting is 0.  When you open a Recordset that contains at least one record, the first record is the current record and BOF and EOF are False; they remain False until you move beyond the beginning or end of the Recordset using the MovePrevious or MoveNext method, respectively.  When you move beyond the beginning or end of the recordset, there is no current record or no record exists.

If you delete the last remaining record in the Recordset object, BOF and EOF may remain False until you attempt to reposition the current record.

If you use the MoveLast method on a Recordset containing records, the last record becomes the current record; if you then use the MoveNext method, the current record becomes invalid and EOF is set to True.  Conversely, if you use the MoveFirst method on a Recordset containing records, the first record becomes the current record; if you then use the MovePrevious method, there is no current record and BOF is set to True.

Typically, when you work with all the records in a Recordset, your code will loop through the records using MoveNext until the EOF property is set to True.

If you use MoveNext while EOF is set to True or MovePrevious while BOF is set to True, an error occurs.

This table shows which Move methods are allowed with different combinations of BOF/EOF.

	MoveFirst, MoveLast	MovePrevious, Move < 0	Move 0	MoveNext, Move > 0
BOF=True, EOF=False	Allowed	Error	Error	Allowed
BOF=False, EOF=True	Allowed	Allowed	Error	Error
Both True	Error	Error	Error	Error
Both False	Allowed	Allowed	Allowed	Allowed
Allowing a Move method doesn't mean that the method will successfully locate a record.  It merely indicates that an attempt to perform the specified Move method is allowed and won't generate an error.  The state of the BOF and EOF flags may change as a result of the attempted Move.

Effect of specific methods on BOF and EOF settings:

An OpenRecordset method internally invokes a MoveFirst.  Therefore, an OpenRecordset on an empty set of records results in BOF and EOF being set to True.  (See the following table for the behavior of a failed MoveFirst method.)

All Move methods that successfully locate a record clear (set to False) both BOF and EOF.

An AddNew method followed by an Update method that successfully inserts a new record will clear BOF, but only if EOF is already set to True.  The state of EOF will always remain unchanged.  As defined by the Microsoft Jet database engine, the current record pointer of an empty recordset is at the end of a file, so any new record is inserted after the current record.

Any Delete method, even if it removes the only remaining record from a recordset, won't change the setting of BOF or EOF.

The effect of Move methods that don't locate a record on BOF and EOF settings is shown in the following table.

	BOF	EOF
MoveFirst, MoveLast	True	True
Move 0	No change	No change
MovePrevious, Move < 0	True	No change
MoveNext, Move > 0	No change	True


See Also

BOFAction, EOFAction Properties

Dynaset Object

EOF Function

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection

Snapshot Object

Table Object


BOF, EOF Properties Example

This example uses the BOF and EOF properties to find the beginning and end of an Orders table.  The example moves through the records from the beginning of the file to the end and then from the end to the beginning.  Notice that there is no current record immediately following the first loop.

Dim MyDB As Database, MyTable As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTable = MyDB.OpenRecordset("Orders")	' Open Recordset.

Do Until MyTable.EOF	' Do until end of file.

MyTable.MoveNext	' Move to next record.

...

Loop

MyTable.MoveLast	' Move to last record to set a current record.

Do Until MyTable.BOF	' Do until beginning of file.

MyTable.MovePrevious	' Move to previous record.

...

Loop

MyTable.Close	' Close table.

MyDb.Close


BOF, EOF Properties Apply To

Dynaset Object

Recordset Object

Snapshot Object

Table Object


Bookmark Property (Data Access)

See Also	Example	Applies To

Returns or sets a bookmark that uniquely identifies the current record in a Recordset object or sets the current record in a Recordset to a valid bookmark.

Syntax

object.Bookmark [= value]

The Bookmark property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression or variant expression that evaluates to a valid bookmark.  (Data type is String or Variant.)

Remarks

You can use the Bookmark property with Recordset objects and with the outdated Dynaset, Snapshot, and Table objects.  For a Recordset based entirely on Microsoft Jet database engine tables, the value of the Bookmarkable property is True and bookmarks can be used.  Other database products may not support bookmarks, however.  For example, you can't use bookmarks in any Recordset based on an attached Paradox table that has no primary key.

When a Recordset object is created or opened, each of its records 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 object's Bookmark property to the value of that variable.

Note   In Visual Basic version 3.0, the Bookmark property is managed as a string.  In Visual Basic version 4.0, the Bookmark property is stored internally as a Byte array.  For this reason, if you attempt to use the Bookmark property in a compare operation, a trappable error will result.  Before accessing the Bookmark property, copy the bookmark values to string variables and make all comparisions using just these string variables.  For example, the following code compares bookmarks in two Recordset objects:

Dim Book1 as String, Book2 as String

Dim Rs1 as Recordset, Rs2 as Recordset

Set Rs1 = Db.OpenRecordset("Titles")

Set Rs2 = Rs1.Clone()

Book1 = Rs1.Bookmark

Book2 = Rs2.Bookmark

If Book1 = Book2 Then Print "This comparison is valid"

There is no limit to the number of bookmarks you can establish.  To create a bookmark for a record other than the current record, move to the desired record and assign the value of the Bookmark property to a String variable that identifies the record.

To make sure the Recordset supports bookmarks, inspect the value of its Bookmarkable property before you use the Bookmark property.  If Bookmarkable is False, the Recordset doesn't support bookmarks, and using the Bookmark property results in a trappable error.

If you create a copy of a Recordset object using the Clone method, the Bookmark settings for the original and the duplicate Recordset are identical and can be used interchangeably.  However, you can't use bookmarks from different Recordset objects interchangeably, even if they were created using the same object or the same SQL statement.

If you set the Bookmark property to a value that represents a deleted record, a trappable error occurs.

To refresh the contents of a record, set the Bookmark property to itself.  (This technique, however, also cancels any pending operations invoked by the Edit or AddNew methods.)  For example:

Rst.Bookmark = Rst.Bookmark

The value of the Bookmark property isn't the same as a record number.

Note   The Bookmark property doesn't apply to forward-only scrolling, snapshot-type Recordset objects.


Bookmark, Bookmarkable Properties Example

This example shows how you can save your place in a Recordset by saving a bookmark.  Once saved, this bookmark can be applied to the Bookmark property to reposition the current record pointer to any location in the Recordset.  The FindYear function looks up a title in a Recordset based on a value and Recordset passed to it and fills a string array with the bookmarks of any records that match.

Function FindYear (YearWanted%, Rs As Recordset, Found()) As Integer

Dim i As Integer

Rs.FindFirst "[Year Published] = " & YearWanted

If Rs.NoMatch Or Rs.Bookmarkable = False Then

FindYear = False

Exit Function

Else

Do Until Rs.NoMatch = True

Found(i) = Rs.Bookmark

Rs.FindNext "[Year Published] = " & YearWanted

i = i + 1

Loop

End If

FindYear = i

End Function


See Also

Bookmarkable Property

Dynaset Object

RecordCount Property

Recordset Object, Recordsets Collection

Snapshot Object

Table Object


Bookmark Property Applies To

Dynaset Object

Recordset Object

Snapshot Object

Table Object


Bookmarkable Property

See Also	Applies To

Returns a value that indicates whether a Recordset object supports bookmarks, which you can set using the Bookmark property.

Syntax

object.Bookmarkable

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Bookmarkable property return values are:

Value	Description

True	The Recordset supports bookmarks.

False	The Recordset doesn't support bookmarks.

Remarks

You can use the Bookmarkable property with Recordset objects and with the outdated Dynaset, Snapshot, and Table objects that support bookmarks.

Check the Bookmarkable property setting before you attempt to set or check the Bookmark property to make sure that the Recordset supports bookmarks.

For a Recordset based entirely on Microsoft Jet database engine tables, the value of the Bookmarkable property is True, and bookmarks can be used except on forward-only scrolling snapshots.  Other database products may not support bookmarks, however.  For example, you can't use bookmarks in any Recordset based on an attached Paradox table that has no primary key.


See Also

Bookmark Property

RecordCount Property

Recordset Object, Recordsets Collection


Bookmarkable Property Applies To

Dynaset Object

Recordset Object

Snapshot Object

Table Object


DateCreated, LastUpdated Properties

See Also	Example	Applies To

DateCreated [image] returns the date and time the base table underlying an object was created.

LastUpdated [image] returns the date and time of the most recent change made to the design of a base table underlying an object.

Syntax

object.DateCreated

object.LastUpdated

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The DateCreated and LastUpdated return values are Variant of VarType 7 (Date).

Remarks

You can use the DateCreated and LastUpdated properties with Recordset, TableDef, QueryDef, and Document objects.  You can also use these properties with the outdated Table object.

The date and time settings are derived from the computer on which the base table was created or last updated.  In a multiuser environment, users should get these settings directly from the file server to avoid discrepancies in the DateCreated and LastUpdated property settings.


See Also

Document Object, Documents Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Table Object

TableDef Object, TableDefs Collection


DateCreated, LastUpdated Properties Example

This example determines the date and time when the Employees table was created and last updated.

Dim Creation As Variant, DesignChange As Variant, MyTable As Recordset, MyDB As Database

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTable = MyDB.OpenRecordset("Employees", dbOpenTable)

Creation = MyTable.DateCreated

DesignChange = MyTable.LastUpdated


DateCreated, LastUpdated Properties Apply To

Document Object

QueryDef Object

Table-Type Recordset

Table Object

TableDef Object


DistinctCount Property

See Also	Example	Applies To

Returns a value that indicates the number of unique values for the Index object that are included in the associated table.

Syntax

object.DistinctCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The DistinctCount property returns a Long data type.

Remarks

Check the DistinctCount property to determine the number of unique values, or keys, in an index.  Any key is counted only once, even though there may be multiple occurrences of that value if the index permits duplicate values.  This information is useful in applications that attempt to optimize data access by evaluating index information.  The number of unique values is also known as the cardinality of an Index object.

The DistinctCount property won't always reflect the actual number of keys at a particular time.  For example, a change caused by a transaction rollback won't be reflected immediately in the DistinctCount property.


 DistinctCount Property Applies To

Index Object


See Also

Index Object, Indexes Collection


DistinctCount Property Example

This example checks the DistinctCount property of the current Index of a TableDef object opened on a table in the database.

Dim MyDB As Database, MyTD As TableDef, MyIND As Index

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB", True)

Set MyTD = MyDB!Customers

Set MyIND = MyTD.Indexes(0)

Debug.Print = MyIND.DistinctCount


Filter Property

See Also	Example	Applies To

Returns or sets a value that determines records included in a subsequently opened Recordset.

Syntax

object.Filter [= value]

The Filter property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that contains the WHERE clause of an SQL statement without the reserved word WHERE.  (Data type is String.)

Remarks

Use the Filter property to apply a filter to the dynaset- or snapshot-type Recordset object or to the outdated Dynaset and Snapshot objects.

You can use the Filter property to restrict the records returned from an existing object when a new Recordset object is opened based on an existing Recordset.

The following example shows how the Filter property can be used to return only the records for customers who live in a particular region:

MyRecordset.Filter = "[Region] = 'NY'"

Set FilteredRecordset = MyRecordset.OpenRecordset()

Notes

In many cases, it's faster to open a new Recordset object using an SQL statement that includes the filter criteria.

Use the U.S. date format (month-day-year) when you filter fields containing dates, even if you're not using the U.S. version of the Microsoft Jet database engine; otherwise, the data may not be filtered as you expect.  You can use the Format function to make this easier.  For example:

MyDS.Filter = "startdate > #" & Format(mydate, "m/d/yy") & "#"


See Also

Dynaset Object

OpenRecordset Method

Recordset Object, Recordsets Collection

Snapshot Object

Sort Property

WHERE Clause (SQL)


Filter Property Example

This example creates a dynaset-type Recordset that contains only records for orders shipped to the United Kingdom.

Dim MyDB As Database, MySet As Recordset, FilteredSet As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MySet = MyDB.OpenRecordset("Orders", dbOpenDynaset)	' Create dynaset-type Recordset.

MySet.Filter = "[Ship Country] = 'UK'"	' Set filter condition.

Set FilteredSet = MySet.OpenRecordset()	' Create filtered dynaset-type Recordset.

Note   To change the contents of MySet, you must set its Filter property, and then open a second Recordset object based on MySet.

Tip   In some situations, it may be more efficient to create the second Recordset object with the desired conditions in one step.  As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement.  This example shows how you can create just one Recordset and obtain the same results as in the preceding example:

Dim MyDB As Database, MySet As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MySet = MyDB.OpenRecordset("SELECT * FROM Orders WHERE [Ship Country] = 'UK';")


Filter Property Applies To

Dynaset Object

Dynaset-Type Recordset

Snapshot Object

Snapshot-Type Recordset


LoginTimeout Property

See Also	Example	Applies To

Returns or sets the number of seconds before an error occurs when you attempt to log in to an ODBC database.

Syntax

object.LoginTimeout [= value]

The LoginTimeout property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An Integer representing the number of seconds before a login timeout error occurs.  The default LoginTimeout setting is 20 seconds.  When LoginTimeout is set to 0, no timeout occurs.

Remarks

When you're attempting to log in to an ODBC database, such as SQL Server, the connection may fail as a result of network errors or because the server isn't running.  Rather than waiting for the default 20 seconds to connect, you can specify how long the Microsoft Jet database engine waits before it produces an error.  Logging on to the server happens implicitly as part of a number of different events, such as running a query on an external server database.

The timeout value is determined by the current setting of the LoginTimeout property in the [ODBC] section of the application initialization (.INI) file.


 See Also

Database Object, Databases Collection

DBEngine Object

ODBCTimeout Property

QueryDef Object, QueryDefs Collection

QueryTimeout Property


LoginTimeout Property Example

This example sets the LoginTimeout property to 120 seconds and then creates and runs a query on a database on an ODBC server.

Dim MyDB As Database, MyQuery As QueryDef, MyRecords As Recordset

DBEngine.LoginTimeout = 120	' Timeout in 2 minutes.

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create query.

Set MyQuery = MyDB.CreateQueryDef("All Cust", "SELECT * FROM Customers;")

MyQuery.Connect = "ODBC;DSN=Human Resources; DATABASE=HRSRVR; UID=Smith; PWD=Sesame"

' Log in to server and run query.

Set MyRecords = MyQuery.OpenRecordset()


LoginTimeout Property Applies To

DBEngine Object


LockEdits Property

See Also	Example	Applies To

Sets or returns a value indicating the locking that is in effect during editing.

Syntax

object.LockEdits [= value]

The LockEdits property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates the type of locking, as described in Settings. (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	(Default) Pessimistic locking is in effect.  The 2K page containing the record you're editing is locked as soon as you use the Edit method.  The page is unlocked when you use the Update or Close method or any of the Move or Find methods.

False	Optimistic locking is in effect for editing.  The 2K page containing the record is locked only while the record is being updated with the Update method.

Remarks

You can use the LockEdits property with dynaset- and table-type Recordset objects and with the outdated Dynaset and Table objects.

If a page is locked, 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.  Other users can read data from locked pages.

If you set LockEdits to False and later use Update while the page is locked by another user, an error occurs.  To see the changes made to your record by another user (and lose your changes), set the Bookmark property of your Recordset object to itself.

When working with ODBC data sources, LockEdits is always set to False (optimistic locking).  The Microsoft Jet database engine has no control over the locking mechanisms used in external database servers.


 See Also

Bookmark Property

Close Method

Dynaset Object

Edit Method

FindFirst, FindLast, FindNext, FindPrevious Methods

IsolateODBCTrans Property

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection

Table Object

Update Method


LockEdits Property Example

This example opens a dynaset-type Recordset and sets its LockEdits property to False.  This enables optimistic locking so other users can change the database records at any time.  Your application triggers a trappable error if the data changes before you use the Update method.

Sub ShowLE()

Dim MyDB As Database, MyRecords As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyRecords = MyDB.OpenRecordset("Table To Update")

MyRecords.LockEdits = False

MyRecords.Edit	' Start editing.

MyRecords!MyField = "New Stuff"

OnError Goto MyEH

MyRecords.Update	' Try to post the changes.

MyRecords.Close

Exit Sub

MyEH:

If Error = 3197 Then	' Data changed.

MsgBox "Data changed."

Resume Next

Else

Msgbox "Some other error."

End If

End Sub


LockEdits Property Applies To

Dynaset Object

Dynaset-Type Recordset

Table Object

Table-Type Recordset


NoMatch Property

See Also	Example	Applies To

Returns a value indicating whether a particular record was found using the Seek method or one of the Find methods.

Syntax

object.NoMatch

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The NoMatch property return values are:

Value	Description

True	The desired record wasn't found.

False	The desired record was found.

Remarks

You can use the NoMatch property with Recordset objects and with the outdated Dynaset, Snapshot, and Table objects.

When you open or create a Recordset object, its NoMatch property is set to False.

To locate a record, use the Seek method on a table-type Recordset or Table object or one of the Find methods on a dynaset- or snapshot-type Recordset, Dynaset, or Snapshot object.  Check the NoMatch property setting to see whether the record was found.

If the Seek operation is unsuccessful and NoMatch is True, the current record will no longer be valid.  Be sure to obtain the current record's bookmark before using the Seek method if you'll need to return to that record.

If the Find operation is unsuccessful and NoMatch is True, the current record is set to the first record of the Recordset.  Be sure to obtain the current record's bookmark before using the Find method if you need to return to that record.

Note   Using any of the Move methods on a Recordset object won't affect its NoMatch property setting.


See Also

BOF, EOF Properties

Dynaset Object

FindFirst, FindLast, FindNext, FindPrevious Methods

Recordset Object, Recordsets Collection

Seek Method

Snapshot Object

Table Object


NoMatch Property Example

This example changes the job title of all sales representatives in an Employees table.  It creates a dynaset-type Recordset and then uses FindFirst and FindNext to locate every record satisfying the criteria for the title.  It prepares each record for editing, changes the title, and saves the change with the Update method.

Dim Criteria As String, SaveHere As String,

Dim MyDB As Database, MySet As Recordset

Criteria = "Title = 'Sales Representative'"   ' Define search criteria.

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create Recordset.

Set MySet = MyDB.OpenRecordset("Employees", dbOpenDynaset)

SaveHere = MySet.Bookmark	' Save Bookmark.

MySet.FindFirst Criteria	' Locate first occurrence.

Do Until MySet.NoMatch	' Loop until no matching records.

MySet.Edit	' Enable editing.

MySet!Title = "Account Executive"	' Change title.

MySet.Update	' Save changes.

MySet.FindNext Criteria	' Locate next record.

Loop	' End of loop.

MySet.Bookmark = SaveHere

Tip   In some situations, using an update query is faster.


NoMatch Property Applies To

Dynaset Object

Recordset Object

Snapshot Object

Table Object


ODBCTimeout Property

See Also	Example	Applies To

Returns or sets the number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is run on an ODBC database.

Syntax

object.ODBCTimeout [= value]

The ODBCTimeout property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer representing the number of seconds the Jet engine waits before a timeout error occurs.  (Data type is Integer.)

Remarks

When you're using an ODBC database, such as SQL Server, there may be delays because of network traffic or heavy use of the ODBC server.  Rather than waiting indefinitely, you can specify how long the Jet engine waits before it produces an error.

The default timeout value is 60 seconds.  The QueryTimeout property setting for a Database object overrides the default setting.

Setting the ODBCTimeout property of a QueryDef object overrides the values specified by the QueryTimeout property setting of the Database containing the QueryDef, but only for that QueryDef.

When ODBCTimeout is set to 0, no timeout occurs.


See Also

QueryDef Object, QueryDefs Collection

QueryTimeout Property


ODBCTimeoutProperty Example

This example sets the ODBCTimeout property to 120 seconds and then creates a query and runs it on a database on an ODBC server.

Dim MyDB As Database, MyQuery As QueryDef, MyRecords As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create query.

Set MyQuery = MyDB.CreateQueryDef("All Cust", "SELECT * FROM Customers;")

MyQuery.Connect = "ODBC;DSN=Human Resources; SERVER=HRSRVR: UID=Smith; PWD=Sesame"

' Log in to server and run query.

MyQuery.ODBCTimeout = 120

Set MyRecords = MyQuery.OpenRecordset()


ODBCTimeout Property Applies To

QueryDef Object


RecordCount Property

See Also	Example	Applies To

Returns the number of records accessed in a Recordset or TableDef object.  This property setting is read-only.

Syntax

object.RecordCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The RecordCount property return value is a Long integer.

Remarks

Use the RecordCount property to find out how many records in a Recordset or TableDef object have been accessed.  RecordCount doesn't indicate how many records are contained in a dynaset- or snapshot-type Recordset until all records have been accessed.

Once the last record has been accessed, the RecordCount property indicates the total number of undeleted records in the Recordset or TableDef.  To force the last record to be accessed, use the MoveLast or FindLast method on the Recordset.  You can also use an SQL Count function to determine the approximate number of records your query will return.

As your application deletes records in a dynaset-type Recordset or Dynaset object, the value of RecordCount decreases.  However, records deleted by other users aren't reflected by RecordCount until the current record is positioned to a deleted record.  If you execute a transaction that affects the RecordCount property setting and subsequently rolls back the transaction, RecordCount won't reflect the actual number of remaining records.

The RecordCount property of a snapshot-type Recordset or Snapshot object isn't affected by changes in the underlying tables.

The RecordCount property of a table-type Recordset, Table, or TableDef object always reflects the number of records in the table and is affected immediately as table records are added and deleted by all users.

A Recordset or TableDef with no records has a RecordCount property setting of 0.

When working with attached tables or ODBC databases, the RecordCount property setting is always -1.

Using the Requery method on a Recordset resets the RecordCount property just as if the query were re-executed.


 See Also

Count Function (SQL)

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection

Requery Method

TableDef Object, TableDefs Collection


RecordCount Property Example

This example creates a Recordset object based on the Employees table and then determines the number of records in the Recordset.

Dim MyDB As Database, MyRecords As Recordset, Total As Long

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyRecords = MyDB.OpenRecordset("Employees")

MyRecords.MoveLast

Total = MyRecords.RecordCount

If Total = -1 Then

Debug.Print "Count not available."

End If


RecordCount Property Applies To

Dynaset Object

Recordset Object

Snapshot Object

Table Object

TableDef Object


Sort Property

See Also	Example	Applies To

Returns or sets the sort order for records in a Recordset object.

Syntax

object.Sort [= value]

The Sort property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that contains the ORDER BY clause of an SQL statement without the reserved words ORDER BY.  (Data type is String.)

Remarks

You can use the Sort property with dynaset- and snapshot-type Recordset objects and with the outdated Dynaset and Snapshot objects.

When you set this property for an object, sorting occurs when a subsequent Recordset is created from that object.  The Sort property setting overrides any sort order specified for a QueryDef object.

The default sort order is ascending (A-Z or 0-100).  The following examples show how you can set the sort order to ascending or descending (Z-A or 100-0):

MySet.Sort = "[Ship Country]"	' Defaults to ascending.

MySet.Sort = "[Ship Country] Asc"

MySet.Sort = "[Ship Country] Desc"

The Sort property doesn't apply to table-type Recordset objects.  To sort a table-type Recordset, use the Index property.

Tip   In many cases, it's faster to open a new Recordset using an SQL statement that includes the sorting criteria.


See Also

Dynaset Object

Dynaset-Type Recordset

Filter Property

Index Property

ORDER BY Clause (SQL)

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Snapshot Object

Snapshot-Type Recordset

SQL Property


Sort Property Example

This example uses the Sort property to set the sort order of a dynaset-type Recordset based on an Orders table.  The records in SortedSet will be in ascending Ship Country order.

Dim MyDB As Database, MySet As Recordset, SortedSet As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MySet = MyDB.OpenRecordset("Orders", dbOpenDynaset)   ' Create dynaset.

MySet.Sort = "[Ship Country]"	' Set sort order.

Set SortedSet = MySet.OpenRecordset()	' Create second dynaset.

Tip   In some situations, it may be more efficient to create the second Recordset object with the desired conditions in one step.  As a general rule, when you know the data you want to select, it's usually more efficient to create a Recordset with an SQL statement.  This example shows how you can create just one Recordset and obtain the same results as in the preceding example:

Dim MyDB As Database, MySet As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MySet = MyDB.OpenRecordset("SELECT * FROM Orders ORDER BY [Ship Country];")


Sort Property Applies To

Dynaset Object

Dynaset-Type Recordset

Snapshot Object

Snapshot-Type Recordset


SQL Property

See Also	Example	Applies To

Returns or sets the SQL statement that defines the query executed by a QueryDef object.

Syntax

object.SQL [= value]

The SQL property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that contains an SQL statement.  (Data type is String.)

Remarks

The SQL property contains the SQL statement that determines how records are selected, grouped, and ordered when you execute the query.  You can use the query to select records to include in a dynaset- or snapshot-type Recordset object or in a Dynaset or Snapshot object.  You can also define bulk queries to modify data without returning records.

Using the ORDER BY or WHERE clause to sort or filter a Recordset is more efficient than using the Sort and Filter properties.

The SQL syntax used in a query must conform to the SQL dialect as defined by the Microsoft Jet database engine unless you create an SQL pass-through query.

Using a QueryDef object is the preferred way to perform SQL pass-through operations on ODBC databases.  By setting the QueryDef object's Connect property to an ODBC data source, you can specify non-Microsoft Jet database SQL in the query passed to the external server.  For example, you can use TRANSACT SQL statements (with Microsoft SQL Server or Sybase SQL Server databases) in the value argument, which won't be processed by the Jet engine.

If the SQL statement includes parameters for the query, you must set these before you execute the query.  Until you reset the parameters, the same parameter values are applied each time you execute the query. Set the parameters by accessing the Parameters collection of the QueryDef object using the following code:

MyQuery.Parameters("Order Date") = "10/11/94"   ' Set parameters.

MyQuery.Parameters("Ship Date") = "11/4/94"


See Also

CreateQueryDef Method

Dynaset Object

Filter Property

OpenRecordset Method

Parameter Object, Parameters Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Retrieving Data Through SQL

Snapshot Object

Sort Property


SQL Property Example

This example creates a query based on an Orders table.  The query selects all orders that have a Freight value greater than 10.

Dim MyDB As Database, MyQuery As QueryDef, MySnapshot As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyQuery = MyDB.CreateQueryDef("Large Freight")   ' Create query.

MyQuery.SQL = "SELECT * FROM Orders WHERE [Freight] > 10;"

' Create snapshot.

Set MySnapshot = MyDB.OpenRecordset("Large Freight", dbOpenSnapshot)


SQL Property Applies To

QueryDef Object


Transactions Property

See Also	Applies To

Returns a value that indicates whether an object supports the recording of a series of changes that can later be rolled back (canceled) or committed (saved).

Syntax

object.Transactions

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Transactions property return values are:

Value	Description

True	The object supports transactions.

False	The object doesn't support transactions.  This is the only value returned for snapshot-type Recordset objects.

Remarks

You can use the Transactions property with dynaset- or snapshot-type Recordset objects and with the outdated Dynaset and Table objects.

If a dynaset or table is based on a Microsoft Jet database engine table, the Transactions property is True and you can use transactions.  Other database engines may not support transactions.  For example, you can't use transactions in a dynaset-type Recordset based on a Paradox table.

Check the Transactions property before using the BeginTrans method on the Recordset object's Workspace object to make sure that transactions are supported.  Using the BeginTrans, CommitTrans, or Rollback methods on a nonsupported object has no effect.


 See Also

BeginTrans, CommitTrans, Rollback Methods

Database Object, Databases Collection

Dynaset Object

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

Workspace Object, Workspaces Collection


Transactions Property Applies To

Database Object

Dynaset Object

Recordset Object

Snapshot Object

Table Object


Updatable Property

See Also	Example	Applies To

Returns a value that indicates whether changes can be made to a data access object.

Syntax

object.Updatable

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Updatable property return values are:

Value	Description

True	The object can be changed or updated.

False	The object can't be changed or updated.  This is the only setting for snapshot-type Recordset and Snapshot objects.

Remarks

Depending on the object, if the Updatable property setting is True, the specified:

Database object can be changed.

QueryDef object query definition can be changed.

Recordset, Dynaset, or Table object records can be updated.

TableDef object table definition can be changed.

You can use the Updatable property with all Recordset objects and with the outdated Dynaset, Snapshot, and Table objects.

The Updatable property setting is always True for a newly created TableDef object and False for an attached TableDef object.  A new TableDef object can be appended only to a database for which the current user has write permission.

Many types of objects can contain fields that can't be updated.  For example, you can create a dynaset-type Recordset in which only some fields can be changed.  These fields can be fixed or contain data that increments automatically, or the dynaset can result from a query that combines updatable and nonupdatable tables.

If the object contains only nonupdatable fields, the value of the Updatable property is False.  When one or more fields are updatable, the property's value is True.  You can edit only the updatable fields.  A trappable error occurs if you try to assign a new value to a nonupdatable field.

The Updatable property of a QueryDef object is set to True if the query definition can be updated, even if the resulting Recordset isn't updatable.

Because an updatable object can contain nonupdatable fields, check the Fields collection of a Recordset object to check the DataUpdatable property of each field before you edit a record in the Recordset.


 See Also

Dynaset Object

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Snapshot Object

Table Object

TableDef Object, TableDefs Collection

Update Method


Updatable Property Example

This example adds a record to a Recordset object if the object's Updatable property setting is True.

Dim MyDB As Database, MyData As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyData = MyDB.OpenRecordset("Unfamiliar Table")

If MyData.Updatable = True Then

MyData.AddNew

MyData("MyField") = "Some new data"

MyData.Update

End If

MyData.Close

MyDB.Close


Updatable Property Applies To

Database Object

Dynaset Object

QueryDef Object

Recordset Object

Snapshot Object

Table Object

TableDef Object


Primary Property

See Also	Example	Applies To

Returns or sets a value that indicates whether an Index object represents a primary index for a table.  The Primary property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.  If the Index object is appended to the TableDef but the TableDef isn't appended to the TableDefs collection, the Index property is read-write.

Syntax

object.Primary [= value]

The Primary property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that specifies a primary index, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	The Index object represents a primary index.

False	The Index object doesn't represent a primary index.

Remarks

A primary index consists of one or more fields that uniquely identify all records in a table in a predefined order.  Because the index field must be unique, the Unique property of the Index object is set to True.  If the primary index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique.  A primary index consists of a key for the table and usually contains the same fields as the primary key.

Tip   You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time.  The Attributes property of each Field object in the Index determines the order of records and consequently determines the access techniques to use for that index.  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 identify each record, and then set the Primary property of the Index object to True.

When you set a primary key for a table, the primary key is automatically defined as the primary index for the table.


Primary Property Example

The example creates a new Table and primary key Index object and then adds the Table to the TableDefs collection of a Database.

Dim Db As Database , Td As TableDef, Idx As Index

Dim Fd1 As Field, Fd2 As Field

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")   ' Open the Database.

Set Td = Db.CreateTableDef("Book Types")

Set Fd1 = Td.CreateField("TypeNum",dbLong)	' Create and Set Fd1 field properties.

 Td.Fields.Append Fd1	' Add Fd1 field to TableDef.

Set Fd2 = Td.CreateField("Type",dbText)	' Create and Set Fd2 field properties.

 Fd2.Size = 15	' Set Size property of text field.

Td.Fields.Append Fd2	' Add Fd2 field to TableDef.

Set Idx = Td.CreateIndex("PrimaryKey")

Idx.Name = "PrimaryKey"	' Set properties in new Index.

Idx.Unique = True

Idx.Primary = True

Idx.Fields = "TypeNum"

Td.Indexes.Append Idx	' Add Index to TableDefs collection.

Db.TableDefs.Append Td	' Add TableDefs to Database.


See Also

Attributes Property

Clustered Property

Index Object, Indexes Collection

Unique Property


Primary Property Applies To

Index Object


Attributes Property

See Also	Applies To

Returns or sets a value that indicates one or more characteristics of a Field object, a Relation object, or a TableDef object.  For an object not yet appended to a collection, this property is read/write.  See Remarks for the more specific read/write characteristics of this property.

Syntax

object.Attributes [= value]

The Attributes property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant specifying the characteristics of an object, as described in Settings.  (Data type is Long.)

Settings

For a Field object, value specifies characteristics of the field represented by the Field object and can be a sum of these constants:

Constant	Description

dbFixedField	The field size is fixed (default for Numeric fields).

dbVariableField	The field size is variable (Text fields only).

dbAutoIncrField	The field value for new records is automatically incremented to a unique Long integer that can't be changed.  Only supported for Jet database tables.

dbUpdatableField	The field value can be changed.

dbDescending	The field is sorted in descending (Z-A or 100-0) order (applies only to a Field object in a Fields collection of an Index object).  If you omit this constant, the field is sorted in ascending (A-Z or 0-100) order (default).

For a Relation object, value specifies characteristics of the relationship represented by the Relation object and can be a sum of these constants:

Constant	Description

dbRelationUnique	Relationship is one-to-one.

dbRelationDontEnforce	Relationship isn't enforced (no referential integrity).

dbRelationInherited	Relationship exists in a noncurrent database that contains the two attached tables.

dbRelationLeft	The relationship is a left join.

dbRelationRight	The relationship is a right join.

dbRelationUpdateCascade	Updates will cascade.

dbRelationDeleteCascade	Deletions will cascade.

Note   If you set the Relation object's Attributes property to activate cascade operations, the Microsoft Jet database engine automatically updates or deletes records in one or more other tables when changes are made to related primary key tables.

For example, suppose you establish a cascade delete relationship between a Customers table and an Orders table.  When you delete records from the Customers table, records in the Orders table related to that customer are also deleted.  In addition, if you establish cascade delete relationships between the Orders table and other tables, records from those tables are automatically deleted when you delete records from the Customers table.

For a TableDef object, value specifies characteristics of the table represented by the TableDef object and can be a sum of these Long constants:

Constant	Description

dbAttachExclusive	For databases that use the Microsoft Jet database engine, indicates the table is an attached table opened for exclusive use.

dbAttachSavePWD	For databases that use the Jet database engine, indicates that the user ID and password for the attached table saved with the connection information.

dbSystemObject	Indicates the table is a system table provided by the Jet engine.  (Read-only.)

dbHiddenObject	Indicates the table is a hidden table provided by the Jet engine (for temporary use).  (Read-only.)

dbAttachedTable	Indicates the table is an attached table from a non-ODBC database, such as a Jet or Paradox database.

dbAttachedODBC	Indicates the table is an attached table from an ODBC database, such as Microsoft SQL Server.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, use of the Attributes property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Read-only

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read-only

For a Relation object, the Attributes property setting is read-only for an object appended to a collection.

For a TableDef object, use of the Attributes property depends on the status of TableDef, as shown in the following table.

TableDef	Usage

Base table	Read-only

Attached table	Read-only

When checking the setting of this property, you can use the And operator to test for a specific attribute.  For example, to determine whether a Field object is fixed-size, you can use this code:

If MyRecordset![FieldName].Attributes And dbFixedField Then...

When setting multiple attributes, you can combine them by summing the appropriate constants.  Any nonmeaningful values are ignored without producing an error.  For example, to use the Attributes property to make the Text field represented by a Field object variable-sized and changeable, you can use this code:

MyRecordset![FieldName].Attributes = dbVariableField + dbUpdatableField


See Also

And Operator

Field Object, Fields Collection

Relation Object, Relations Collection

TableDef Object, TableDefs Collection


Attributes Property Applies To

Field Object

Relation Object

TableDef Object


CollatingOrder Property

See Also	Applies To

Returns a value that specifies the sequence of the sort order in text for string comparison or sorting.  This property setting is read-only.

Syntax

object.CollatingOrder

The CollatingOrder property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant that specifies the sort order, as described in Settings.  (Data type is Integer.)

Settings

The values returned are:

Setting	Description

dbSortGeneral	Use the General (English, French, German, Portuguese, Italian, and Modern Spanish) sort order.

dbSortArabic	Use the Arabic sort order.

dbSortCyrillic	Use the Russian sort order.

dbSortCzech	Use the Czech sort order.

dbSortDutch	Use the Dutch sort order.

dbSortGreek	Use the Greek sort order.

dbSortHebrew	Use the Hebrew sort order.

dbSortHungarian	Use the Hungarian sort order.

dbSortIcelandic	Use the Icelandic sort order.

dbSortJapanese	Use the Japanese sort order.

dbSortNeutral	Use the neutral sort order.

dbSortNorwdan	Use the Norwegian or Danish sort order.

dbSortPDXIntl	Use the Paradox International sort order.

dbSortPDXNor	Use the Paradox Norwegian or Danish sort order.

dbSortPDXSwe	Use the Paradox Swedish or Finnish sort order.

dbSortPolish	Use the Polish sort order.

dbSortSpanish	Use the Spanish sort order.

dbSortSwedFin	Use the Swedish or Finnish sort order.

dbSortTurkish	Use the Turkish sort order.

dbSortUndefined	The sort order is undefined or unknown.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, use of the CollatingOrder property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read only

The CollatingOrder property setting corresponds to the locale argument of the CreateDatabase method when the database was created or the CompactDatabase method when the database was most recently compacted.

Check the CollatingOrder property setting of a Database or Field object to find out the string comparison method for the database or field.  You can set the CollatingOrder property of a new Field object if you want the setting of the Field object to differ from that of the Database object that contains it.

The CollatingOrder and Attributes property settings of a Field object in a Fields collection of an Index object together determine the sequence and direction of the sort order in an index.  However, you can't set a collating order for an individual index [image] only for an entire table.

You can use the setting of the CollatingOrder property as the compare argument in the StrComp and InStr functions.


See Also

Attributes Property

Database Object, Databases Collection

Field Object, Fields Collection

InStr Function

StrComp Function


CollatingOrder Property Applies To

Database Object

Field Object


OrdinalPosition Property

See Also	Applies To

Returns or sets the relative position of a Field object within the Fields collection to which it is appended. For an object not yet appended to the Fields collection, this property is read/write.  See Remarks for the more specific read/write characteristics of this property.

Syntax

object.OrdinalPosition [= value]

The OrdinalPosition property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer that specifies the numeric order of fields.  The default is 0.  (Data type is Integer.)

Remarks

For a Field object, use of the OrdinalPosition property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

Generally, the ordinal position of an object that you append to a collection depends on the order in which you append the object.  The first appended object is in the first position (0), the second appended object is in the second position (1), and so on.  The last appended object is in ordinal position count - 1, where count - 1 is the number of objects in the collection as specified by the Count property setting.

Using the OrdinalPosition property, you can specify an ordinal position for new Field objects that differs from the order in which you append those objects to a collection.  This enables you to specify a field order for your tables, queries, and recordsets when you use them in an application.  For example, the order in which fields are returned in a SELECT * query would be determined by the current OrdinalPosition values.

You can permanently reset the order in which fields are returned in recordsets by setting the OrdinalPosition property.  The Microsoft Jet database engine accepts any positive integer for the OrdinalPosition property.  A trappable error occurs with negative numbers.

Two or more Field objects in the same collection can have the same OrdinalPosition value, in which case they will be ordered alphabetically.  For example, if you have a field named Age set to 4 and you set a second field named Weight to 4, Weight is returned after Age.

You can specify a number that is greater than the number of fields -1.  The field will be returned in an order relative to the largest number.  For example, if you set a field's OrdinalPosition property to 20 (and there are only 5 fields) and you've set the OrdinalPosition property for two other fields to 10 and 30, respectively, the field set to 20 is returned between the fields set to 10 and 30.

After you change the OrdinalPosition property setting, you can use the property to return the current setting.  However, the fields aren't reordered until the Fields collection is repopulated.  For example:

TableDefs("Titles").Fields(0).OrdinalPosition = 3

This code changes which Field object is referenced in the fourth position (0 relative).  Because Field(0) was Title, Field(2) now refers to Title, and Field(0) refers to the first (lowest) field in the sequence.

It is far clearer to reference Field objects by their Name property.  For example, this code assigns the AU_ID field to the third field position:

TableDefs("Titles").Fields("AU_ID").OrdinalPosition = 2

Note   After you change the OrdinalPosition property setting of an object in the Fields collection, you may need to use the Refresh method on the collection before the new property setting takes effect.


See Also

Count Property

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Refresh Method

TableDef Object, TableDefs Collection


OrdinalPosition Property Applies To

Field Object


Required Property

See Also	Applies To

Returns or sets a value that indicates whether a Field or Index object requires a non-Null value.  For an object not yet appended to a collection, this property is read/write.  For an Index object, this property setting is read-only for objects appended to Indexes collections in Recordset and TableDef objects.  See Remarks for the more specific read/write characteristics of this property.

Syntax

object.Required [= value]

The Required property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression indicating whether an object requires a non-Null value, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	A Null value isn't allowed.

False	A Null value is allowed.

Remarks

For a Field object, use of the Required property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

For a Field object, you can use the Required property along with the AllowZeroLength, ValidateOnSet, or ValidationRule property to determine the validity of the Value property setting for that Field object.  If Required is set to False, the field can contain Null values as well as values that meet the conditions specified by the AllowZeroLength and ValidationRule property settings.

Tip   When you can set this property for either an Index object or a Field object, set it for the Field object.  The validity of the property setting for a Field object is checked before that of an Index object.


See Also

AllowZeroLength Property

Field Object, Fields Collection

Index Object, Indexes Collection

QueryDef Object, QueryDefs Collection

Required Property

ValidateOnSet Property

ValidationRule Property

ValidationText Property

Value Property


Required Property Applies To

Field Object

Index Object


QueryTimeout Property

See Also	Example	Applies To

Returns or sets a value that specifies the number of seconds the Microsoft Jet database engine waits before a timeout error occurs when a query is executed on an ODBC database.

Syntax

object.QueryTimeout [= value]

The QueryTimeout property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer representing the number of seconds the Jet database engine waits before timing out and returning an error.  (Data type is Integer.)

Remarks

When you're using an ODBC database, such as SQL Server, 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 Jet engine produces an error.

When used with a Database object, the QueryTimeout property specifies a global value for all queries associated with the database.

The default timeout value is always 60 seconds, regardless of any .INI file settings.  The setting of QueryTimeout on a Database object overrides the default value.


 See Also

Database Object, Databases Collection

ODBCTimeout Property


QueryTimeout Property Example

This example opens the specified database and sets the QueryTimeout property to 120 seconds.

Dim MyDB As Database

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

MyDB.QueryTimeout = 120


QueryTimeout Property Applies To

Database Object


LastModified Property

See Also	Applies To

Returns a bookmark indicating the most recently added or changed record.

Syntax

object.LastModified

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The return value for this property is a Variant or String data type.  You can use LastModified to move to the most recently added or updated record.

Use the LastModified property with Recordset objects and with the outdated Dynaset, Snapshot, and Table objects.


 See Also

Bookmark Property

Bookmarkable Property

DateCreated, LastUpdated Properties

Recordset Object, Recordsets Collection


LastModified Property Applies To

Dynaset Object

Dynaset-Type Recordset

Snapshot Object

Table Object

Table-Type Recordset


SourceField, SourceTable Properties

See Also	Example	Applies To

SourceField [image] returns a value that indicates the name of the field that is the original source of the data for a Field object.

SourceTable [image] returns a value that indicates the name of the table that is the original source of the data for a Field object.

This property is not available at design time and is read-only at runtime.

Syntax

object.SourceField [= value]

object.SourceTable [= value]

The SourceField and SourceTable property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression specifying the name of the field or table that is the source of data.  (Data type is String.)

Remarks

For a Field object, use of the SourceField and SourceTable properties depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read-only

These properties indicate the original field and table names associated with a Field object.  For example, you could use these properties to determine the original source of the data in a query field whose name is unrelated to the name of the field in the underlying table.


See Also

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

SourceTableName Property

TableDef Object, TableDefs Collection


SourceField, SourceTable Properties Example

This example creates a Recordset object using an SQL statement that creates aliases for fields in two different tables in the database.  The example then prints the name of the field, the original table, and the original field.

Function SourceInfo () As Integer

Dim MyDatabase As Database

Dim MyRecordset As Recordset, MyField As Field

Dim MySQL As String, I As Integer

' Open database.

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Construct SQL statement.

MySQL = "SELECT [Employee ID] As EmpID, [Customer ID] As CustID"

MySQL = MySQL & " FROM Employees, Customers;"

Set MyRecordset = MyDatabase.OpenRecordset(MySQL)   ' Generate recordset.

For I = 0 To MyRecordset.Fields.Count - 1

Set MyField = MyRecordset.Fields(I)

Debug.Print MyField.Name	' Print field name.

Debug.Print MyField.SourceTable	' Print original table name.

Debug.Print MyField.SourceField	' Print original field name.

Next I

SourceInfo = True

End Function


SourceField, SourceTable Properties Apply To

Field Object


SourceTableName Property

See Also	Example	Applies To

Returns or sets a value that specifies the name of an attached table or the name of the base table on which the query is based as it exists in the original source of the data.  This property setting is read-only for a base table and read/write for an attached table or an object not appended to a collection.

Syntax

object.SourceTableName [= value]

The SourceTableName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies a table name.  For a base table, the setting is a zero-length string ("").  (Data type is String.)


See Also

Connect Property

OpenDatabase Method

RefreshLink Method

SourceField, SourceTable Properties

TableDef Object, TableDefs Collection


Connect, SourceTableName Properties; TableDef Object Example

This example creates a TableDef object in the specified database; sets its Connect, Name, and SourceTableName properties; and then appends it to the TableDefs collection.

Function ConnectSource () As Integer

Dim MyDatabase As Database

Dim MyTableDef As TableDef

Dim I As Integer

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTableDef = MyDatabase.CreateTableDef("PDXAuthor")

' Attach Paradox table Author in database C:\PDX\PUBLISH.

MyTableDef.Connect = "Paradox 4.X;DATABASE=C:\PDX\PUBLISH"

MyTableDef.SourceTableName = "Author"

MyDatabase.TableDefs.Append MyTableDef	' Attach table.

ConnectSource = True

End Function


SourceTableName Property Applies To

TableDef Object


Connect Property

See Also	Example	Applies To

Returns or sets a value that provides information about the source of an open database, a database used in a pass-through query, or an attached table. For QueryDef objects, Database objects, attached tables, and TableDef objects not yet appended to a collection, this property setting is read/write. For a base table, this property is read-only.

Syntax

object.Connect = [databasetype;[parameters;]]

The Connect property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

databasetype	A string expression that specifies a database type.  For Jet databases, exclude this argument; if you specify parameters, use a semicolon (;) as a placeholder.  (Data type is String.)

parameters	A string expression that specifies additional parameters to pass to ODBC or installable ISAM drivers.  Use semicolons to separate parameters.  (Data type is String.)

Settings

The Connect property setting is a String composed of a database type specifier and zero or more parameters separated by semicolons.  The Connect property is used to pass additional information to ODBC and certain ISAM drivers as needed.  It isn't used for Jet databases, except for those containing attached tables, so as to allow SQL pass-through queries.

To perform an SQL pass-through query on a table attached to your .MDB file, you must first set the Connect property of the attached table's database to a valid ODBC connect string.

For a TableDef object that represents an attached table, the Connect property setting consists of one or two parts (a database type specifier and a path to the database), each of which ends with a semicolon.

The path as shown in the table below is the full path for the directory containing the database files and must be preceded by the identifier "DATABASE=".  In some cases (as with Jet, Btrieve, and Microsoft Excel databases) a specific filename is included in the database path argument.

The following table shows possible database types and their corresponding database specifiers and paths for the Connect property setting:

Database type	Specifier	Path
Database using the Jet database engine	";"	"drive:\path\filename.MDB"
dBASE III	"dBASE III;"	"drive:\path"
dBASE IV	"dBASE IV;"	"drive:\path"
Paradox 3.x	"Paradox 3.x;"	"drive:\path"
Paradox 4.x	"Paradox 4.x;"	"drive:\path"
Btrieve	"Btrieve;"	"drive:\path\filename.DDF"
FoxPro 2.0	"FoxPro 2.0;"	"drive:\path"
FoxPro 2.5	"FoxPro 2.5;"	"drive:\path"
FoxPro 2.6	"FoxPro 2.6;"	"drive:\path"
Excel 3.0	"Excel 3.0;"	"drive:\path\filename.XLS"
Excel 4.0	"Excel 4.0;"	"drive:\path\filename.XLS"
Excel 5.0	"Excel 5.0;"	"drive:\path\filename.XLS"
Text	"Text;"	"drive:\path"
ODBC	"ODBC; DATABASE=defaultdatabase; UID=user; PWD=password; DSN=datasourcename LOGINTIMEOUT=seconds"  (This may not be a complete connection string for all servers; it's just an example.)	None
Remarks

If the specifier is only "ODBC;", a dialog box listing all registered ODBC data source names is displayed by the ODBC driver so the user can select a database.

If a password is required but not provided in the Connect property setting, a login dialog box is displayed the first time a table is accessed by the ODBC driver and again if the connection is closed and reopened.

For Jet database base tables, the Connect property setting is a zero-length string ("").

You can set the Connect property for a Database object by providing a source argument to the OpenDatabase method.  You can check the setting to determine the type, path, user ID, Password, or ODBC data source of the database.

For a QueryDef object, you use the Connect property with the ReturnsRecords property to create an ODBC SQL pass-through query.  The databasetype of the connection string is "ODBC;", and the remainder of the string contains information specific to the ODBC driver used to access the remote data.  For more information, see the documentation for the specific driver.

Note    The Connect property must be set before the ReturnsRecords property is set.


See Also

Accessing External Databases

Database Object, Databases Collection

OpenDatabase Method

QueryDef Object, QueryDefs Collection

ReturnsRecords Property

TableDef Object, TableDefs Collection


Connect Property Applies To

Data Control

Database Object

QueryDef Object

TableDef Object


Fields Property

See Also	Example	Applies To

Returns or sets a value indicating which TableDef fields are key fields in an index.  This property is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Note   The Fields property is included in this version for compatibility with earlier versions.  It's recommended that you use Field objects in the Fields collection of an Index object instead.  In this case, you create a Field object for each of the key fields and append them to the Fields collection of an Index object to indicate index keys.

Syntax

index.Fields [ = fieldlist[;fieldlist] ]

The Fields property syntax has these parts:

Part	Description

index	An object expression that evaluates to an object in the Applies To list.

fieldlist	A string expression containing a semicolon-delimited (;) list of field names that make up the index.  (Data type is String.)

Remarks

In the list of field names, you can precede a name with a plus sign (+) or a minus sign (-) to indicate ascending (A-Z or 0-100) or descending (Z-A or 100-0) sort order, respectively, for the field.  The default sort order is ascending.  You can enclose field names in brackets ([ ]).  You must use brackets to enclose a field name containing a semicolon.

An Index object can have one or more fields representing index keys for each record.


Fields Property Applies To

Index Object


 See Also

Append Method

Field Object, Fields Collection

Index Object, Indexes Collection

Name Property

Unique Property


Fields Property Example

This example adds a new index to the Authors table.

Dim TempIndex As Index	' Create new Index object.

Set TempIndex = MyDb.TableDefs("Authors").CreateIndex("Full Name")

TempIndex.Fields = "LName;FName"

TempIndex.Unique = True

' Append the new Index to the Indexes collection.

MyDb.TableDefs("Authors").Indexes.Append TempIndex


Size Property (Data Access)

See Also	Example	Applies To

Returns or sets a value that indicates the maximum size, in bytes, of a Field object that contains text or the fixed size of a Field object that contains text or numeric values.  For an object not yet appended to the Fields collection, this property is read/write.

Syntax

object.Size [= value]

The Size property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value indicating the maximum size, as described in Settings.  (Data type is Integer.)

Settings

The setting for value depends on the Type property setting of the Field object and can be one of these integer values:

Setting	Value	Description

dbBoolean	1	True/False

dbByte	1	Byte

dbInteger	2	Integer

dbLong	4	Long

dbCurrency	8	Currency

dbSingle	4	Single

dbDouble	8	Double

dbDate	8	Date/Time

dbText	1-255	Text

dbLongBinary	0	Long Binary (OLE Object)

dbMemo	0	Memo

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

For a Field object, use of the Size property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read-only

When you create a Field object with a data type other than Text, the Type property setting automatically determines the Size property setting, and you don't need to set the Size property.  For OLE Object and Memo Field objects, Size is always set to 0.  For a Field object with the Text data type, Size can be set to any integer up to 255 where the Size property sets the maximum size for the Field.

For OLE Object and Memo Field objects, use the FieldSize method of the Field object to determine the size of the data in a specific record.  The maximum size of an OLE Object or Memo field is limited only by your system resources or the maximum size of the database.


 See Also

Attributes Property

Field Object, Fields Collection

Index Object, Indexes Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Relation Object, Relations Collection

Type Property


Size, Type Properties Example

This example creates a new Field object with a Text field type, sets its Name property to Fax Phone and its Size property to 20, and appends the new object to the Fields collection of the Employees table in the TableDefs collection of the database.

Function SizeType() As Integer

Dim MyDatabase As Database

Dim MyField As Field, MyTableDef As TableDef

' Open database.

Set MyDatabase = Workspaces(0).OpenDatabase("MYDB.MDB")

' Get existing table reference.

Set MyTableDef = MyDatabase!Employees

' Create Field object.

Set MyField = MyTableDef.CreateField("Fax Phone")

' Set field properties.

MyField.Type = dbText

MyField.Size = 20

' Append MyField to Fields collection.

MyTableDef.Fields.Append MyField

SizeType = True

End Function

You can also use the CreateField method if you provide name, type, and size as arguments.

Set MyField = MyTableDef.CreateField("Fax Phone", dbText, 20)


Size Property Applies To

Field Object


Type Property (Data Access)

See Also	Example	Applies To

Returns or sets a value that indicates the operational type or data type of an object.  For a Field or Property object, this property setting is read/write until the object is appended to a collection or to another object, after which it's read-only.  For a Parameter, QueryDef, or Recordset object, the property setting is read-only.

Syntax

object.Type [= value]

The Type property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer or constant that indicates an operational or data type, as described in Settings.  (Data type is Integer.)

Settings

For a Field, Parameter, or Property object, the settings for value are:

Value	Setting	Description

8	dbDate	Date/Time

10	dbText	Text

12	dbMemo	Memo

1	dbBoolean	Yes/No

3	dbInteger	Integer

4	dbLong	Long

5	dbCurrency	Currency

6	dbSingle	Single

7	dbDouble	Double

2	dbByte	Byte

11	dbLongBinary	Long Binary (OLE Object)

Note   A Long Binary data type is the same as a String.  However, it's recommended that you use the Variant data type instead of  Long Binary (OLE Object ) data types because doing so enables you to store Nulls.

For a QueryDef object, the settings for value are:

Setting	Query type

dbQSelect	Select

dbQAction	Action

dbQCrosstab	Crosstab

dbQDelete	Delete

dbQUpdate	Update

dbQAppend	Append

dbQMakeTable	Make-table

dbQDDL	Data-definition

dbQSQLPassThrough	Pass-through

dbQSetOperation	Union

dbQSPTBulk	Used with dbQSQLPassThrough to specify a query that doesn't return records.

For a Recordset object, the settings for value are:

Setting	Recordset type

dbOpenTable	Table

dbOpenDynaset	Dynaset

dbOpenSnapshot	Snapshot

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Depending on the object, the Type property indicates:

Object	Type indicates

Field, Parameter, Property	Object data type

QueryDef	Type of query

Recordset	Type of Recordset

When you append a new Field, Parameter, or Property object to the collection of an Index, QueryDef, Recordset, or TableDef object, an error occurs if the underlying database doesn't support the data type specified for the new object.

Note   To create an SQL pass-through query, you don't set the dbSQLPassThrough flag.  This flag is set by the Microsoft Jet database engine when you create a QueryDef object and set the Connect property.


 See Also

Field Object, Fields Collection

Parameter Object, Parameters Collection

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Data Type Summary


Type Property Applies To

Field Object

Parameter Object

Property Object

QueryDef Object

Recordset Object


Unique Property

See Also	Example	Applies To

Returns or sets a value that indicates whether an Index object represents a unique (key) index for a table.  For an Index object, this property setting is read/write until the object is appended to a collection, after which it's read-only.

Syntax

object.Unique [= value]

The Unique property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that specifies a unique index, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	The Index object represents a unique index.

False	The Index object represents a non-unique index.

Remarks

A unique index consists of one or more fields that logically arrange all records in a table in a unique, predefined order.  If the index consists of one field, values in that field must be unique for the entire table.  If the index consists of more than one field, each field can contain duplicate values, but each combination of values from all the indexed fields must be unique.

If both the Unique and Primary properties of an Index object are set to True, the index is unique and primary:  It uniquely identifies all records in the table in a predefined, logical order.  If the Primary property is set to False, the index is a secondary index.  Secondary indexes (both key and nonkey) logically arrange records in a predefined order without serving as an identifier for records in the table.

Tips

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time.

Records read from tables without indexes are returned in no particular sequence.

The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that Index.

A unique index helps optimize finding records.

Indexes don't affect the physical order of a base table [image] indexes only affect how the records are accessed by the Table object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.


 See Also

Attributes Property

Clustered Property

Index Object, Indexes Collection

Primary Property


Unique Property Applies To

Index Object


Index Property (Data Access)

See Also	Example	Applies To

Returns or sets a value that indicates the name of the current Index object in a table-type Recordset or the outdated Table object.

Syntax

object.Index [ = indexname ]

The Index property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

indexname	A string expression that evaluates to the name of an Index object in the Indexes collection of the Table or table-type Recordset object's TableDef.  (Data type is String.)

Remarks

Records in base tables aren't stored in any particular order.  Setting the Index property changes the order of records returned from the database; it doesn't affect the order in which the records are stored.

For example, to set the Index property prior to using the Seek method on the Titles table:

Dim Tb as Recordset, Db as Database

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set Tb = Db.OpenRecordset("Titles",dbTable)

Tb.Index = "PubID"

Tb.Seek "=", 3

The specified Index object must already be defined.  If you set the Index property to an Index object that doesn't exist or if the Index property isn't set when you use the Seek method, a trappable error occurs.

Examine the Indexes collection of a TableDef object to determine what Index objects are available to table-type Recordset objects created from that TableDef.

You can create a new index for the table by creating a new Index object, setting its properties, appending it to the Indexes collection of the underlying TableDef, and then reopening the Recordset.

Records returned from a Table object can be ordered only by the indexes defined for the underlying TableDef.  To sort records in some other order, you can open a dynaset- or snapshot-type Recordset using an SQL statement with an ORDER BY clause.

The Index property of an element of a control array isn't the same as the Index property of a data access object.

Tips

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record or creating a  Recordset can take a long time.  On the other hand, creating too many indexes slows down update, append, and delete operations as all indexes are automatically updated.

Records read from tables without indexes are returned in no particular sequence.

The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index.

A unique index helps optimize finding records.

Indexes don't affect the physical order of a base table [image] indexes only affect how the records are accessed by the Table object when a particular index is chosen or when the Microsoft Jet database engine creates Recordset objects.


Index, Unique Properties Example

This example adds a new index to a TableDef object, makes that index the current index, and invokes the Seek method based on that index.  The names of the Field objects created and appended to the Fields collection of the Index object correspond to the names of current fields in the table.

Dim Tb As Recordset, Ix As Index, Fd As Field

Dim MyDb As Database

Set MyDb = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set Ix = MyDb.TableDefs("Publishers").CreateIndex("PubID Name")

Set Fd = Ix.CreateField("PubID")

Ix.Fields.Append Fd

Set Fd = Ix.CreateField("Name")

Ix.Fields.Append Fd

Ix.Unique = True

Debug.Print Ix.Fields	' Show Fields property.

' Append the new Index to the Indexes collection.

MyDb.TableDefs("Publishers").Indexes.Append Ix

Set Tb = MyDb.OpenRecordset("Publishers",dbOpenTable)  'Open the table.

Tb.Index = "PubID Name"	' Set table's current index.

Tb.Seek "=", "27", "Yourdon Press"	' Look for Publisher.

If Tb.NoMatch Then

Tb.MoveFirst

Debug.Print "Not found"

Else

Debug.Print Tb.Name

End If

Tb.Close

This example sets the index for MyTable to the primary key (PrimaryKey is the default name of an Index object if the primary key is set in the table's Design view).  Next, it locates the record with a matching key field value of 10,050.  Notice that the current index must be set before certain operations, such as the Seek method, can be performed.

Dim MyDB As Database, MyTable As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTable = MyDB.OpenRecordset("Orders", dbOpenTable)   ' Open Recordset.

MyTable.Index = "PrimaryKey"	' Set current index.

MyTable.Seek "=", 10050	' Locate record.

...

MyTable.Close	' Close Recordset.


Index Property Applies To

Table Object

Table-Type Recordset


See Also

Append Method

Index Object, Indexes Collection

Primary Property

Recordset Object, Recordsets Collection

Seek Method

Sort Property

TableDef Object, TableDefs Collection


DefaultValue Property

See Also	Applies To

Returns or sets the default value of a Field object.  For a Field object not yet appended to the Fields collection, this property is read/write.  See Remarks for the more specific characteristics of this property.

Syntax

object.DefaultValue [= value]

The DefaultValue property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that can contain a maximum of 255 characters.  It can be either text or an expression.  If the property setting is an expression, it can't contain user-defined functions; Microsoft Jet database engine domain aggregate functions; SQL aggregate functions; or references to queries, forms, or other Field objects.  (Data type is String.)

Remarks

For a Field object, use of the DefaultValue property depends on the object that contains the Fields collection that the Field object is appended to, as shown in the following table.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

When a new record is created, the DefaultValue property setting is automatically entered as the value for the field.  You can change the field value by setting its Value property.

The DefaultValue property doesn't apply to Counter and OLE Object fields.


See Also

AllowZeroLength Property

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Required Property

TableDef Object, TableDefs Collection

ValidateOnSet Property

ValidationRule Property

ValidationText Property

Value Property


DefaultValue Property Applies To

DBGrid Control

Field Object


CacheSize, CacheStart Properties

See Also	Example	Applies To

CacheSize [image] returns or sets a value that specifies the number of records in a dynaset-type Recordset containing data to be locally cached from an ODBC data source.

CacheStart [image] returns or sets a value that specifies the bookmark of the first record in the Recordset to be cached.

Syntax

object.CacheSize [= value]

object.CacheStart [= value]

The CacheSize and CacheStart property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A number or string expression.  The setting for CacheSize specifies the number of records and must be between 5 and 1200, but not greater than available memory.  A typical value is 100.  A setting of 0 turns off caching.  (Data type is Long.)  The setting for CacheStart specifies a bookmark (Data type is String.)

Remarks

Data caching improves the performance of an application that retrieves data from a remote server through dynaset-type Recordset objects.  A cache is a space in local memory that holds the data most recently retrieved from the server in the event that the data will be requested again while the application is running.  When data is requested, the Microsoft Jet database engine checks the cache for the requested data first rather than retrieving it from the server, which takes more time.  Data that doesn't come from an ODBC data source isn't saved in the cache.

Any ODBC data source, such as an attached table, can have a local cache.  To create the cache, open a Recordset object from the remote data source, set the CacheSize and CacheStart properties, and then use the FillCache method or step through the records using the Move methods.

The CacheSize property setting can be based on the number of records your application can work with at one time.  For example, if you're using a Recordset as the source of the data to be displayed on screen, you could set its CacheSize property to 20 to display 20 records at one time.

The CacheStart property setting is the bookmark of the first record in the Recordset to be cached.  You can use the bookmark of any record to set the CacheStart property.  Make the record you want to start the cache with the current record, establish a bookmark for that record, and set the CacheStart property to the bookmark.

The Jet database engine requests records within the cache range from the cache, and it requests records outside the cache range from the server.

Notes

 	Records retrieved from the cache don't reflect changes made concurrently to the source data by other users.

To force an update of all the cached data, set the CacheSize property of the Recordset to 0, set it to the size of the cache you originally requested, and then use the FillCache method.


 See Also

Bookmark Property

Bookmarkable Property

Database Object, Databases Collection

FillCache Method

Recordset Object, Recordsets Collection


CacheSize, CacheStart Properties Apply To

Dynaset-Type Recordset (ODBC only)


Clustered Property

See Also	Applies To

Returns or sets a value that indicates whether an Index object represents a clustering index for a table.  This property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Syntax

object.Clustered [= value]

The Clustered property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates a clustering index, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	The Index object represents a clustering index.

False	The Index object doesn't represent a clustering index.

Remarks

A clustering index consists of one or more nonkey fields that, taken together, arrange all records in a table in a predefined order.  A clustering index provides efficient access to records in a table in which the index values may not be unique.

Notes

The Clustered property is ignored for databases that use the Microsoft Jet database engine because the Jet database engine doesn't support clustering indexes.

This property can't be used for ODBC data sources.

You don't have to create indexes for tables, but in large, unindexed tables, accessing a specific record can take a long time.  The Attributes property of each Field object in the Index object determines the order of records and consequently determines the access techniques to use for that index.


See Also

Attributes Property

Index Object, Indexes Collection

Primary Property

Unique Property


Clustered Property Applies To

Index Object (non-Jet databases only)


DataUpdatable Property

See Also	Applies To

Returns a value that indicates whether the data in the field represented by a Field object is updatable.

Syntax

object.DataUpdatable

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The DataUpdatable property return values are:

Value	Description

True	The data in the field is updatable.

False	The data in the field isn't updatable.

Remarks

Use this property to determine whether you can change the Value property setting of a Field object.  The DataUpdatable property is always read-only.  It is not supported on Field objects appended to the Fields collection of Index and Relation objects.


See Also

Field Object, Fields Collection

Recordset Object, Recordsets Collection

Updatable Property

Value Property


DataUpdatable Property Applies To

Field Object


ForeignName Property

See Also	Example	Applies To

Returns or sets a value that, in a relationship, specifies the name of the Field object in a foreign table that corresponds to a field in a primary table.

Syntax

object.ForeignName [= value]

The ForeignName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that evaluates to the name of a Field in the associated TableDef object's Fields collection.  (Data type is String.)

Remarks

Only a Field object that belongs to a Fields collection contained by a Relation object can support the ForeignName property.  If the Relation isn't appended to the Database, but the Field is appended to the Relation, you can still change the ForeignName property.  Once the Relation object is appended to the database, the properties of the Field object are read-only.

The Name and ForeignName property value settings for a Field object specify the names of the corresponding fields in the primary and foreign tables of a relationship.  The Table and ForeignTable property value argument settings of a Relation object determine the primary and foreign tables of a relationship.

For example, if you had a list of valid part codes (in a field named PartNo) stored in a ValidParts table, you could establish a relationship with an OrderItem table such that, if a part code was entered into the OrderItem table, it must exist in the ValidParts table.  If the part code did not exist in the ValidParts table and you had not indicated No Enforcement in the Attributes property, a trappable error would occur.

In this case, the ValidParts table would be an example of a Primary table, so the ForeignTable property of the Relation object would be set to OrderItem and the Table property of the Relation object would be set to ValidParts.  The Name property and ForeignName property of the Field object would both be PartNo.


See Also

Field Object, Fields Collection

ForeignTable Property

Name Property

Relation Object, Relations Collection

Table Property


ForeignName, ForeignTable, Table Properties Example

This example shows how you can use the ForeignName, ForeignTable, and Table properties when you create a relationship between two existing tables [image] in this case, Table1 (the primary table) and Table2 (the foreign table) in the specified database.  Field1 is the primary key in Table1, and Field2 is a foreign key in Table2.  The relationship is one-to-many and referential integrity is enforced.

Function ForeignNameTable () As Integer

Dim MyDb As Database

Dim MyField As Field, MyRelation As Relation

' Get database.

Set MyDb = Workspaces(0).OpenDatabase("MYDB.MDB")

' Create new relationship and set its properties.

Set MyRelation = MyDb.CreateRelation("MyRelation")

MyRelation.Table = "Table1"

MyRelation.ForeignTable = "Table2"

' Create field and set its properties.

Set MyField = MyRelation.CreateField("Field1")

MyField.ForeignName = "Field2"

' Append field to relation and relation to database.

MyRelation.Fields.Append MyField

MyDb.Relations.Append MyRelation

End Function


ForeignName Property Applies To

Field Object


ForeignTable Property

See Also	Example	Applies To

Specifies the name of the foreign table in a relationship.  This property setting is read/write for a new Relation object not yet appended to a collection and read-only for an existing Relation object in the Relations collection.

Syntax

object.ForeignTable [= value]

The ForeignTable property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that evaluates to the name of a table in the Database object's TableDefs collection.  (Data type is String.)

Remarks

The ForeignTable property setting of a Relation object is the Name property setting of the TableDef or QueryDef object that represents the foreign table or query; the Table property setting is the Name property setting of the TableDef or QueryDef object that represents the primary table or query.

For example, if you had a list of valid part codes (in a field named PartNo) and stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table, it must exist in the ValidParts table.  If the part code did not exist in the ValidParts table and you had not indicated No Enforcement in the Attributes property, a trappable error would occur.

In this case, the ValidParts table would be an example of a foreign table, so the ForeignTable property of the Relation object would be set to ValidParts and the Table property of the Relation object would be set to OrderItem.  The Name property and ForeignName property of the Field object would both be set to PartNo.


See Also

ForeignName Property

Name Property

QueryDef Object, QueryDefs Collection

Relation Object, Relations Collection

Table Property

TableDef Object, TableDefs Collection


ForeignTable Property Applies To

Relation Object


Inherited Property (Data Access)

See Also	Example	Applies To

Returns or sets a value that indicates whether a Property object is inherited from an underlying object.  This property setting is read-only.

Syntax

object.Inherited

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Inherited property return values are:

Value	Description

True	The Property object is inherited.

False	The Property object isn't inherited.  For built-in Property objects that represent predefined properties, False is the only setting.

Remarks

You can use the Inherited property to determine whether a user-defined property was created for the object it applies to or whether the property was created for another object.  For example, suppose you create a property for a QueryDef object and then open a Recordset object from the QueryDef.  This property will be part of the Recordset object's Properties collection, and its Inherited property will be set to True because the property was created for the QueryDef, not the Recordset.


See Also

CreateProperty Method

Property Object, Properties Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

TableDef Object, TableDefs Collection


Inherited, Value Properties Example

This example creates a Recordset object from a QueryDef object, creates a new property, and indicates whether the property is inherited.  Then the example prints the name of each field in the Recordset and, for each property of each field, it prints the Name, Type, Value, and Inherited property value settings.

Dim MyDB As Database, MyQueryDef As QueryDef, MyRecordset As _

Recordset, MyProperty As Property

Dim X, Y As Integer

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyQueryDef = MyDB.QueryDefs(0)

Set MyProperty = MyQueryDef.CreateProperty("Moose",dbBoolean, True)

MyQueryDef.Properties.Append MyProperty

Set MyRecordset = MyQueryDef.OpenRecordset()

Debug.Print "Is MyQueryDef.Moose inherited? "; MyQueryDef.Properties("Moose").Inherited

Debug.Print "Is MyRecordset.Moose inherited? "; MyRecordset.Properties("Moose").Inherited

For X = 0 To MyRecordset.Fields.Count - 1

Debug.Print MyRecordset.Fields(X).Name

On Error Resume Next

For Y = 0 To MyRecordset.Fields(X).Properties.Count - 1

Debug.Print MyRecordset.Fields(X).Properties(Y).Name

Debug.Print MyRecordset.Fields(X).Properties(Y).Type

Debug.Print MyRecordset.Fields(X).Properties(Y).Value

Debug.Print MyRecordset.Fields(X).Properties(Y).Inherited

Next Y

Next X


Inherited Property Applies To

Container Object

Property Object


IgnoreNulls Property

See Also	Applies To

Returns or sets a value that indicates whether there are index entries for records that have Null values in their index fields.  This property setting is read/write for a new Index object not yet appended to a collection and read-only for an existing Index object in an Indexes collection.

Syntax

object.IgnoreNulls [= value]

The IgnoreNulls property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates index entries, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	Fields with Null values don't have an index entry.

False	Fields with Null values have an index entry.

Remarks

To make searching for records using a field faster, you can define an index for the field.  If you allow Null entries in an indexed field and expect many of the entries to be Null, you can set the IgnoreNulls property for the Index object to True to reduce the amount of storage space that the index uses.

The IgnoreNulls property setting and the Required property setting together determine whether a record with a Null index value has an index entry, as the following table shows.

IgnoreNulls	Required	Null in index field

True	False	Null value allowed; no index entry added.

False	False	Null value allowed; index entry added.

True or False	True	Null value not allowed; no index entry added.


See Also

Index Object, Indexes Collection

Required Property


IgnoreNulls Property Applies To

Index Object


Owner Property

See Also	Example	Applies To

Returns or sets a value that specifies the owner of the object.

Syntax

object.Owner [= value]

The Owner property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that evaluates to either the name of a User object in the Users collection or the name of a Group object in the Groups collection.  (Data type is String.)

Remarks

The owner of an object has certain access privileges denied to other users.  The Owner property setting can be changed at any time by any individual user account (represented by a User object) or group of user accounts (represented by a Group object) having the appropriate permissions.


See Also

Activating Security

Container Object, Containers Collection

Document Object, Documents Collection

Group Object, Groups Collection

Permissions Property

User Object, Users Collection


Owner Property Example

This example changes the Owner property setting of a Document object after determining whether the current user has the appropriate permissions to do so.

Dim MyDB As Database, MyDoc As Document

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyDoc = MyDB.Containers(0).Documents(0)

If (MyDoc.Permissions And dbSecWriteOwner) <> 0  Then

MyDoc.Owner = "SomebodyElse"

End If


Owner Property Applies To

Container Object

Document Object


Permissions Property

See Also	Example	Applies To

Returns or sets a value that establishes the permissions for the user or group identified by the UserName property of the Container or Document object.

Syntax

object.Permissions [= value]

The Permissions property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant that establishes permissions, as described in Settings.

Settings

For any Container or Document object, the settings for value are:

Constant	Description

dbSecNoAccess	No access to the object.

dbSecFullAccess	Full access to the object.

dbSecDelete	Can delete the object.

dbSecReadSec	Can read the object's security-related information.

dbSecWriteSec	Can alter access permissions.

dbSecWriteOwner	Can change the Owner property setting.

For the Tables Container or any Document in a Documents collection, the settings for value are:

Constant	Description

dbSecCreate	Can create new documents (valid only with a Container object).

dbSecReadDef	Can read the table definition including column and index information.

dbSecWriteDef	Can modify or delete the table definition including column and index information.

dbSecRetrieveData	Can retrieve data from the Document.

dbSecInsertData	Can add records.

dbSecReplaceData	Can modify records.

dbSecDeleteData	Can delete records.

For the Databases Container object or any Document object in a Documents collection, the settings for value are:

Constant	User or group

dbSecDBCreate	Can create new databases (valid only on the databases Container object in the system database [SYSTEM.MDW]) .

dbSecDBExclusive	Exclusive access.

dbSecDBOpen	Can open the database.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

Use this property to establish or determine the type of read/write/modify permissions the user specified by the UserName property has for a Container or Document object.

A Document object inherits the permissions for users from its Container, provided the Inherited property of the Container is set for those users or for a group to which the users belong.  By setting a Document object's Permissions and UserName properties later, you can further refine the access control behavior of your object.


 See Also

Activating Security

Container Object, Containers Collection

Document Object, Documents Collection

Inherited Property

UserName Property


Permissions Property Example

This example prints the Permissions property setting of a Document object for the current user.

Dim MyDB As Database, MyDoc As Document

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyDoc = MyDB.Containers(0).Documents("MyDoc")

Debug.Print MyDoc.Permissions


Permissions Property Applies To

Container Object

Document Object


Restartable Property

See Also	Example	Applies To

Returns a value that indicates whether a Recordset object supports the Requery method, which re-executes the query on which the Recordset is based.

Syntax

object.Restartable

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Restartable property return values are:

Value	Description

True	The Recordset supports the Requery method.

False	The Recordset doesn't support the Requery method.  This is the only setting for table-type Recordset objects.

Remarks

Check the Restartable property before using the Requery method on a Recordset.  If the object's Restartable property is set to False, use the OpenRecordset method on the underlying QueryDef to re-execute the query.

You can use the Requery method to update a Recordset object's underlying parameter query after the parameter values have been changed.


See Also

OpenRecordset Method

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Requery Method


Restartable Property, Requery Method Example

This example determines the Restartable property setting of a dynaset-type Recordset and then uses the Requery method on the Recordset.

Dim MyDB As Database, MyData As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyData = MyDB.OpenRecordset("Table That Changes Often", dbOpenDynaset)

If MyData.Restartable = True Then

MyData.Requery

Else

MyData.Close

End If


Restartable Property Applies To

Recordset Object


Table Property

See Also	Example	Applies To

Returns or sets a value that specifies the name of a Relation object's primary table.  This name is the Name property setting of a TableDef or QueryDef object.  The Table property setting is read/write for a new Relation object not yet appended to a collection and read-only for an existing Relation object in a Relations collection.

Syntax

object.Table [= value]

The Table property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that evaluates to the name of a table in the TableDefs collection.  (Data type is String.)

Remarks

Use the Table property with the ForeignTable property to define a Relation object, which represents the relationship between fields in two tables or queries.  Set the Table property to the Name property setting of the primary TableDef or QueryDef object, and set the ForeignTable property to the Name property setting of the foreign (referencing) TableDef or QueryDef object.  The Attributes property determines the type of relationship between the two objects.

For example, if you had a list of valid part codes (in a field named PartNo) and stored in a ValidParts table, you could establish a relationship with an OrderItem table such that if a part code was entered into the OrderItem table, it must exist in the ValidParts table.  If the part code didn't exist in the ValidParts table and you had not indicated No Enforcement in the Attributes property, a trappable error would occur.

In this case, the ValidParts table is an example of a foreign table, so the ForeignTable property of the Relation object would be set to ValidParts and the Table property of the Relation object would be set to OrderItem.  The Name property and ForeignName property of the Field object would both be set to Part Number.

The picture shown below illustrates how the ValidParts table is primary because it's referenced by the OrderItem table.


See Also

Attributes Property

Field Object, Fields Collection

ForeignTable Property

Name Property

QueryDef Object, QueryDefs Collection

Relation Object, Relations Collection

TableDef Object, TableDefs Collection


Table Property Applies To

Relation Object


UserName Property

See Also	Example	Applies To

Returns or sets a value that represents a user or group of users or the owner of a Workspace object.  For Container and Document objects, this property setting is read/write.  For a Workspace object, this property setting is read/write for an object not yet appended to a collection and read-only for an existing Workspace object.

Syntax

object.UserName [= value]

The UserName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that evaluates to the name of a User object in the Users collection or a Group object in the Groups collection.  (Data type is String.)

Remarks

Depending on the type of object, the UserName property represents:

A user or group of users when you manipulate the access permissions of a Container object or a Document object.

The owner of a Workspace object.  For Container and Document objects, you use the UserName property with the Permissions property to establish read or write permissions.

To find or set the permissions for a particular user or group of users, first set the UserName property to the user or group name that you want to examine.  Then check the Permissions property setting to determine what permissions that user or group of users has, or set the Permissions property to change the permissions.

For a Workspace object, check the UserName property setting to determine the owner of the Workspace object.  Set the UserName property to establish the owner of the Workspace object before you append the object to the Workspaces collection.


See Also

Activating Security

Append Method

Container Object, Containers Collection

Document Object, Documents Collection

Inherited Property

Password Property

Permissions Property

Workspace Object, Workspaces Collection


UserName Property Example

This example sets the access permissions for a table named MyTable in the specified database for a user named Millicent to read-only.  The code then checks to see if Millicent has permission to add records.

Dim MyWorkspace As Workspace, MyDatabase As Database

Dim MyDocument As Document

...

Set MyWorkspace = DBEngine.Workspaces(0)

Set MyDatabase = MyWorkspace.OpenDatabase("MYDB.MDB")

...

Set MyDocument = MyDatabase.Containers("Tables")![MyTable]

MyDocument.UserName = "Millicent"

MyDocument.Permissions = dbSecRetrieveData

If(MyDocument.Permissions and dbSecInsertData) > 0 Then

Debug.Print "Millicent can insert data."

Else

Debug.Print "Millicent can't insert data."

End If

...


UserName Property Applies To

Container Object

Document Object

Workspace Object


ValidateOnSet Property

See Also	Applies To

Returns or sets a value that specifies whether or not the value of a Field object is immediately validated when the object's Value property is set.  Only Field objects in Recordset objects support the ValidateOnSet property as read/write.

Syntax

object.ValidateOnSet [= value]

The ValidateOnSet property syntax has these parts:

Part	Description

object	An object expression that evaluates to a Field object of a table-type or dynaset-type Recordset object.

value	A Boolean expression that indicates whether a value is validated, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	Validate when the property is set.

False	Validate when the record is updated.

Remarks

When ValidateOnSet is set to True, the validation rule specified by the ValidationRule property setting of the Field object is checked when you set the object's Value property.

A Recordset object can contain a Fields collection with several Field objects whose ValidationRule property value settings involve a combination of the fields.  When ValidateOnSet is set to False, you can set the Value property of each field independently and perform validation using the final value settings when the record is updated.

The ValidateOnSet property isn't supported on Field objects associated with the outdated Dynaset or Table objects.


See Also

AllowZeroLength Property

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Required Property

ValidationRule Property

ValidationText Property

Value Property


ValidateOnSet Property Applies To

Field Object


ValidationRule Property

See Also	Applies To

Returns or sets a value that validates the data in a field as it's changed or added to a table.  For an object not yet appended to the Fields collection, this property is read/write.  See Remarks for the more specific read/write characteristics of this property.

Syntax

object.ValidationRule [= value]

The ValidationRule property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that describes a comparison in the form of an SQL WHERE clause without the WHERE reserved word. (Data type is String.)

Remarks

The ValidationRule property determines whether or not valid data is in the associated field.  If the data is not legal, a trappable run-time error occurs.  The returned error message is the text of the ValidationText property, if specified, or the text of the expression specified by ValidationRule.

For a Field object, use of the ValidationRule property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

For a Recordset object, use of the ValidationRule property is read-only.  For a TableDef object, use of the ValidationRule property depends on the status of the TableDef, as the following table shows.

TableDef	Usage

Base table	Read/write

Attached table	Read-only

Validation is supported only for databases that use the Microsoft Jet database engine.

The string expression specified by the ValidationRule property of a Field object can refer only to that Field.  The expression can't refer to user-defined functions, domain aggregate functions, SQL aggregate functions, or queries.  To set a Field object's ValidationRule property when its ValidateOnSet property setting is True, the expression must successfully parse (with the field name as an implied operand) and evaluate to True.  If its ValidateOnSet property setting is False, the ValidationRule property setting is ignored.

The ValidationRule property of a Recordset or TableDef object can refer to multiple fields in that object.  The restrictions noted earlier in this topic for the Field object apply.

For a table-type Recordset object, ValidationRule takes the value of the ValidationRule property setting of the TableDef object that you use to create the table-type Recordset object.

For a TableDef object based on an attached table, ValidationRule takes the value of the underlying base table.  If the underlying base table doesn't support validation, the value of this property is a zero-length string ("").

The ValidationRule property isn't supported for Field objects associated with the outdated Dynaset or Table objects.


See Also

Update Method

ValidateOnSet Property

ValidationText Property


ValidationRule Property Applies To

Field Object

Recordset Object

TableDef Object


Value Property (Data Access)

See Also	Example	Applies To

Returns or sets the value of an object.

Syntax

object.Value [= value]

The Value property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An expression that evaluates to a value appropriate for the data type, as specified by the Type property of an object.  (Data type is Variant.)

Remarks

Generally, Value is used to retrieve and alter data in Recordset objects.

The Value property is the default property of the Field, Parameter, and Property objects.  Therefore, the following lines of code are equivalent (assuming Field1 is at the first ordinal position):

X = MyRecordset!Field1

X = MyRecordset!Field1.Value

X = MyRecordset(0)

X = MyRecordset(0).Value

X = MyRecordset("Field1").Value

X = MyRecordset("Field1")

F$ = "Field1" : X = MyRecordset(F$).Value

X = MyRecordset(F$)


See Also

Field Object, Fields Collection

Name Property

Parameter Object, Parameters Collection

Property Object, Properties Collection

Updatable Property

Value Property


Value Property Applies To

Field Object

Parameter Object

Property Object


Version Property

See Also	Example	Applies To

Returns a value that indicates the version of the database or database engine associated with the object.  This property setting is read-only.

Syntax

object.Version

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Version property return value is a string expression that evaluates to a value, depending on the object specified:

Database object [image] identifies the data format version of an open database.

DBEngine object [image] identifies the version number of the Microsoft Jet database engine.

Remarks

For a Database object, this property identifies the version of the Jet database engine that created the database.

The setting of the Version property represents the version number in the form "major.minor"; for example, "2.0".  The product version number (for example, 2.0) consists of the version number (2), a period, and the release number (0).


See Also

CreateDatabase Method

Database Object, Databases Collection

DBEngine Object


Version Property Example

This example checks the version number of the Jet database engine and splits it into the version number and release number.  The example doesn't check for an invalid string.

Dim DBVersion As String, Version As String, Release As String

Dim DotLocation As Integer

...

DBVersion = DBEngine.Version

DotLocation = InStr(DBVersion, ".")

Version = Left$(DBVersion, DotLocation - 1)

Release = Right$(DBVersion, Len(DBVersion) - DotLocation)

...


Version Property Applies To

Database Object

DBEngine Object


ValidationText Property

See Also	Applies To

Returns or sets a value that specifies the text of the message that your application displays if the value of a Field object doesn't satisfy the validation rule specified by the ValidationRule property setting.

For an object not yet appended to a collection, this property is read/write.  For a Recordset object, this property setting is read-only. For a TableDef object, this property setting is read-only for an attached table and read/write for a base table.  See Remarks for the more specific read/write characteristics of this property.

Syntax

object.ValidationText [= value]

The ValidationText property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies the text displayed if an entered value is invalid.  (Data type is String.)

Remarks

For a Field object, use of the ValidationText property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write


See Also

AllowZeroLength Property

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Required Property

TableDef Object, TableDefs Collection

ValidationRule Property

Value Property


ValidationText Property Applies To

Field Object

Recordset Object

TableDef Object


Name Property (Data Access)

See Also	Example	Applies To

Returns or sets a user-defined name for a data access object.  For an object not appended to a collection, this property is read/write.  See Remarks for the more specific read/write characteristics of this property.

Syntax

object.Name [= value]

The Name property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies a name.  The name must start with a letter and can contain a maximum of 40 characters.  It can include numbers and underscore characters but can't include punctuation or spaces.  (Data type is String.)

Remarks

TableDef and QueryDef objects can't share the same name, nor can User and Group objects.

The Name property of a Recordset object opened using an SQL statement is the first 256 characters of the SQL statement.

You can use an object's Name property with the Dim statement in code to create other instances of the object.

Note   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.

The read/write usage of the Name property depends on the type of object it applies to, but regardless of the object type, the Name property is read-only, once the object has been appended to a collection.

Object	Usage

Container	Read-only

Database	Read-only

Document	Read-only

Field	Read/write

   Index.Field	Read-only

   QueryDef.Field	Read-only

   Recordset.Field	Read-only

   TableDef.Field (native)	Read/write

   TableDef.Field (attached)	Read-only

   Relation.Field	Read-only

Group	Read/write

Index	Read/write

   Recordset.Index	Read/write

Parameter	Read-only

Property (built-in)	Read-only

Property (user-defined)	Read/write

QueryDef	Read/write

Recordset	Read-only

Relation	Read/write

TableDef (native)	Read/write

TableDef (attached)	Read/write

User	Read/write

Workspace	Read/write


 See Also

CreateDatabase Method

CreateField Method

CreateIndex Method

CreateQueryDef Method

CreateTableDef Method


Name Property Example

This example creates a TableDef object and then names it Parts ID.

Dim MyDB As Database, MyTD As TableDef, Fd as Field

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTD = MyDB.CreateTableDef("")

MyTD.Name = "Parts ID"

...	' Create fields.

MyDB.TableDefs.Append MyTD


Name Property Applies To

Column Object

Container Object

Database Object

DBEngine Object

Dynaset Object

Field Object

Group Object

Index Object

Parameter Object

Property Object

QueryDef Object

Recordset Object

Snapshot Object

Table Object

TableDef Object

Workspace Object

User Object


V1xNullBehavior Property

See Also	Applies To

Returns or sets a value that indicates whether zero-length strings ("") used in code to fill Text or Memo fields are converted to Null.  This property applies only to Microsoft Jet database engine version 1.x databases that have been converted to Microsoft Jet engine version 2.5 or 3.0 databases.

Note   The Jet engine automatically creates this property when it converts a version 1.x database to a version 2.5 or 3.0 database.

Syntax

object.V1xNullBehavior [= value]

The V1xNullBehavior property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates whether zero-length strings are converted to Null, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	Zero-length strings are converted to Null.

False	Zero-length strings aren't converted to Null.

You can only set this property using Visual Basic.

Note   If you change this property setting, you must close and then reopen the database for your change to take effect.

Remarks

For fastest performance, modify code that sets any Text or Memo fields to zero-length strings so that the fields are set to Null instead, and remove V1xNullBehavior from the Properties collection.


 See Also

ActiveForm Property

Caption Property

Dim Statement

Index Property

LinkTopic Property

Me

Text Property


V1xNullBehavior Property Applies To

Database Object


AllowZeroLength Property

See Also	Applies To

Returns or sets a value that indicates whether a zero-length string ("") is a valid setting for the Value property of a Field object with a Text or Memo data type.  For an object not yet appended to the Fields collection, this property is read/write.

Syntax

object.AllowZeroLength [= value]

The AllowZeroLength property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates if a value is valid, as described in Settings. (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	A zero-length string is a valid value.

False	A zero-length string isn't a valid value.

Remarks

For a Field object, use of the AllowZeroLength property depends on the object that contains the Fields collection that the Field object is appended to, as the following table shows.

Object appended to	Usage

Index	Not supported

QueryDef	Read-only

Recordset	Read-only

Relation	Not supported

TableDef	Read/write

You can set this property to False to ensure that you can't use a zero-length string to set the Value property of a Field object.

You can use this property along with the Required, ValidateOnSet, or ValidationRule property to determine the validity of a value in a field.


See Also

Field Object, Fields Collection

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Required Property

TableDef Object, TableDefs Collection

ValidateOnSet Property

ValidationRule Property

ValidationText Property

Value Property


AllowZeroLength Property Applies To

Field Object


PercentPosition Property

See Also	Example	Applies To

Returns or sets a value that indicates or changes the approximate location of the current record in the Recordset object based on a percentage of the records in the Recordset.

Syntax

object.PercentPosition [= value]

The PercentPosition property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A number between 0.0 and 100.00.  (Data type is Single.)

Remarks

To indicate or change the approximate position of the current record in a Recordset, you can check or set the PercentPosition property.  When working with a dynaset- or snapshot-type Recordset, first populate the Recordset by moving to the last record before you set or check the PercentPosition property.  If you use the PercentPosition property before fully populating the Recordset, the amount of movement is relative to the number of records accessed as indicated by the RecordCount property setting.  You can move to the last record using the MoveLast or FindLast method.

Note   Using the PercentPosition property to move the current record to a specific record in a Recordset isn't recommended [image] the Bookmark property or AbsolutePosition property is better suited for this task.

Once you set the PercentPosition property to a value, the record at the approximate position corresponding to that value becomes current, and the PercentPosition property is reset to a value that reflects the approximate position of the current record.  For example, if your Recordset contains only five records, and you set its PercentPosition value to 77, the value returned from the PercentPosition property may be 80, not 77.

The PercentPosition property applies to all three types of Recordset objects (except for forward-only scrolling snapshots).  However, the PercentPosition property of a table-type Recordset always returns 50 if you haven't set the Index property of the Recordset to a valid value.  The PercentPosition property doesn't work with the outdated Dynaset, Snapshot, and Table objects.

You can use the PercentPosition property with a scroll bar on a form or text box to indicate the location of the current record in a Recordset.

Note   The PercentPosition property isnt available on a forward-only scrolling snapshot-type Recordset, or on a Recordset opened from a pass-through query against a remote database.


See Also

Bookmark Property

Index Property

Move Method

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection

TableDef Object, TableDefs Collection


PercentPosition Property Example

This example displays the current position of a record in a Recordset in a label named CurrentPosition.

Dim MyDB As Database, MyTable As Recordset

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set MyTable = MyDB.OpenRecordset("Employees",dbOpenTable)   ' Open table.

MyTable.Index = "Last Name"

' Set current index.

MyTable.MoveLast

...

CurrentPosition.Caption = MyTable.PercentPosition   ' Display current position.


PercentPosition Property Applies To

Recordset Object


Foreign Property

See Also	Applies To

Returns a value that indicates whether an Index object represents a foreign key in a table.  This property setting is read-only.

Syntax

object.Foreign

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Foreign property return values are:

Value	Description

True	The Index object represents a foreign key.

False	The Index object doesn't represent a foreign key.

Remarks

A foreign key consists of one or more fields in a foreign table that uniquely identify all rows in a primary table.

The Microsoft Jet database engine creates an Index object for the foreign table and sets the Foreign property when you create a relationship that enforces referential integrity.


 See Also

Index Object, Indexes Collection

Primary Property

Relation Object, Relations Collection

TableDef Object, TableDefs Collection


Foreign Property Applies To

Index Object


Password Property

See Also	Applies To

This property is not supported in this version of Visual Basic.

You can neither examine nor set passwords using this property.  To set a password for a Workspace object, use the CreateWorkspace method. Use the NewPassword method to change the Password property setting for an existing User object.  To clear a password, set the newpassword argument of the NewPassword method to a zero-length string ("").


See Also

Activating Security

NewPassword Method

Permissions Property

PID Property

User Object, Users Collection

UserName Property

Workspace Object, Workspaces Collection


Password Property Applies To

User Object

Workspace Object


PID Property

See Also	Applies To

Sets the personal identifier (PID) for either a group or a user account.  This property setting is write-only for new objects not yet appended to a collection, and it's not available for existing objects.

Syntax

object.PID = [value]

The PID property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression containing 4-20 alphanumeric characters.  (Data type is String.)

Remarks

Set the PID property along with the Name property when you create a new Group object.  Set the PID property along with the Name and Password properties when you create a new User object.


See Also

Activating Security

Group Object, Groups Collection

Name Property

Password Property

User Object, Users Collection

Workspace Object, Workspaces Collection


PID Property Applies To

Group Object

User Object


ReturnsRecords Property

See Also	Example	Applies To

Returns or sets a value that indicates whether an SQL pass-through query to an external database returns records.

Syntax

object.ReturnsRecords [= value]

The ReturnsRecords property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates whether records are returned, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	(Default) The pass-through query returns records.

False	The pass-through query doesn't return records.

Remarks

Not all SQL pass-through queries to external databases return records.  For example, an SQL UPDATE statement updates records without returning records, while an SQL SELECT statement does return records.  If the query returns records, set ReturnsRecords to True; if the query doesn't return records, set ReturnsRecords to False.

Note   The Connect property must be set before the ReturnsRecords property is set.


 See Also

Connect Property

QueryDef Object, QueryDefs Collection

QueryTimeout Property

SQL Property


ReturnsRecords Property Example

The following example creates an SQL pass-through query that returns records from an external database.

Dim MyDB As Database, PassThrough As QueryDef

Set MyDB = Workspaces(0).OpenDatabase("MYDB.MDB")

Set PassThrough = MyDB.CreateQueryDef("October _

Orders","SELECT * From Orders WHERE ShipCity = 'London'")

MyDB.Connect = "ODBC; DSN=MySQLDBDSN;  " _

& " UID=Chrissy;PWD=FourOh;"

PassThrough.ReturnsRecords = True


ReturnsRecords Property Applies To

QueryDef Object


LogMessages Property

See Also	Applies To

Sets a value that specifies if the messages returned from an ODBC database are recorded.  This property is user-defined and is read/write once created and installed.

Note   The user must install this property using the CreateProperty method on a QueryDef object.

Syntax

object.LogMessages [= value]

The LogMessages property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that specifies whether messages are recorded, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	ODBC-generated messages are recorded.

False	ODBC-generated messages aren't recorded.

Remarks

Some pass-through queries can return messages in addition to data.  If you set the LogMessages property to True, the Microsoft Jet database engine creates a table that contains returned messages.  The table name is the user name concatenated with a hyphen (-) and a sequential number starting at 00.  For example, because the default user name is ADMIN, the tables returned would be named ADMIN-00, ADMIN-01, and so on.

If you expect the query to return messages, create and append a user-defined LogMessages property for the QueryDef, and set its type to BOOLEAN and its value to True.

Once you've processed the results from these tables, you may want to delete them from the database along with the temporary query used to create them.

The LogMessages property setting must be defined as dbBoolean (Boolean) when created.


 See Also

Accessing External Databases

QueryDef Object, QueryDefs Collection


LogMessages Property Applies To

QueryDef Object


IsolateODBCTrans Property

See Also	Example	Applies To

Returns or sets a value that indicates whether multiple transactions that involve the same ODBC database are isolated.

Syntax

object.IsolateODBCTrans [= value]

The IsolateODBCTrans property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates whether transactions are isolated, as described in Settings.  (Data type is Boolean.)

Settings

The settings for value are:

Setting	Description

True	Isolate transactions involving the same ODBC database.

False	(Default) Don't isolate transactions involving the same ODBC database.

Remarks

In some situations, you need to have multiple simultaneous transactions pending on the same ODBC database.  To do this, you need to open a separate Workspace for each transaction.  Although each Workspace can have its own ODBC connection to the database, this slows system performance.  Because transaction isolation isn't normally required, ODBC connections from multiple Workspace objects opened by the same user are shared by default.

Some ODBC servers, such as Microsoft SQL Server, don't allow simultaneous transactions on a single connection.  If you need to have more than one transaction at a time pending against such a database, set the IsolateODBCTrans property to True on each Workspace as soon as you open it.  This forces a separate ODBC connection for each Workspace.


IsolateODBCTrans Property Applies To

Workspace Object


See Also

BeginTrans, CommitTrans, Rollback Methods

Workspace Object, Workspaces Collection


IsolateODBCTrans Property Example

This example opens a Workspace and sets IsolateODBCTrans to True before starting a transaction.

Dim MyDB As Database, MyWS As Workspace, MyQuery As QueryDef

Set MyWS = DBEngine.Workspaces(0)

MyWS.IsolateODBCTrans = True

MyWS.BeginTrans

' Execute query to ODBC database and complete transaction.

...


AbsolutePosition Property

See Also	Example	Applies To

Returns or sets the relative record number of a Recordset object's current record.

Syntax

object.AbsolutePosition [= value]

The AbsolutePosition property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer from 0 to the number of records in the Recordset.  Corresponds to the ordinal position of the current record in the Recordset specified by object.  (Data type is Long.)

Remarks

The AbsolutePosition property enables you to position the current record pointer to a specific record based on its ordinal position in a dynaset- or snapshot-type Recordset.  You can also determine the current record number by checking the AbsolutePosition property setting.

The AbsolutePosition property value is zero-based [image] a setting of 0 refers to the first record in the Recordset.  Setting a value greater than the number of populated records causes a trappable error.  You can determine the number of populated records in the Recordset by checking the RecordCount property setting.

If there is no current record, as when there are no records in the Recordset, -1 is returned.  If the current record is deleted, the AbsolutePosition property value isn't defined, and a trappable error occurs if it's referenced.  New records are added to the end of the sequence.

Note   This property isn't intended to be used as a surrogate record number.  Bookmarks are still the recommended way of retaining and returning to a given position and are the only way to position the current record across all types of Recordset objects.  In particular, the position of a given record changes when record(s) preceding it are deleted.  There is also no assurance that a given record will have the same absolute position if the Recordset is re-created again because the order of individual records within a Recordset isn't guaranteed unless it's created with an SQL statement using an ORDER BY clause.

The AbsolutePosition property isn't available on a forward-only scrolling snapshot-type Recordset, or on a Recordset opened from a pass-through query against a remote database.


AbsolutePosition Property Applies To

Dynaset-Type Recordset

Recordset Object

Snapshot-Type Recordset


See Also

Bookmark Property

PercentPosition Property

Populating Recordsets

RecordCount Property

Recordset Object, Recordsets Collection


AbsolutePosition Property Example

This example positions the current record to the nth record in a dynaset-type Recordset object.

Function MoveToRecord (N as Long, Rs as Recordset) As Integer

Rs.MoveLast	' Fully populate the Recordset.

If Rs.RecordCount > N Then

Rs.AbsolutePosition = N

MoveToRecord = True

Else

MoveToRecord = False

End If

Db.Close


DefaultUser, DefaultPassword Properties

See Also	Applies To

Set the user name and password used by the Microsoft Jet database engine when a Workspace object is created without a specific user name and password.

Syntax

object.DefaultPassword = value

object.DefaultUser = value

The DefaultUser and DefaultPassword property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression containing a valid user name or password.  (Data type is String.)

A user name can be 1-20 characters long and include alphabetic characters, accented characters, numbers, spaces, and symbols except for: " (quotation marks), / (forward slash), \ (backslash), [ ] (brackets), : (colon), | (pipe), < (less-than sign), > (greater-than sign), + (plus sign), = (equal sign), ; (semicolon), , ( comma), ? (question mark), * (asterisk), leading spaces, and control characters (ASCII 00 to ASCII 31).

A password may be up to 14 characters long and may contain any character except ASCII 0.

Remarks

User names aren't usually case-sensitive; however, if you're re-creating a user account that was deleted or created in a different workgroup, the user name must be an exact case-sensitive match of the original name.  User names aren't case-sensitive.

Typically, the CreateWorkspace method is used to create a Workspace object with a given user name and password.  However, for backward compatibility with earlier versions and for convenience when secured databases aren't being used, the Jet engine automatically creates a Workspace object when needed if one isn't already open.  In this case, the DefaultUser and DefaultPassword values are used.

Note   The default UserName and Password properties are unaffected if the Workspace object is referenced before you set the DefaultUser and DefaultPassword properties.

By default, the DefaultUser property is set to admin and the DefaultPassword property is set to a zero-length string ("").

The DefaultUser and DefaultPassword properties are set when you call the outdated SetDefaultWorkspace method.


DefaultUser, DefaultPassword Properties Apply To

DBEngine Object


See Also

Activating Security

SetDefaultWorkspace Statement


EditMode Property

See Also	Example	Applies To

Returns a value that indicates the state of editing for the current record.

Syntax

object.EditMode

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The EditMode property returns the following values:

Value	Description

dbEditNone	No editing operation is in progress.

dbEditInProgress	Edit method has been invoked, and the current record is in the copy buffer.

dbEditAdd	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 constants are listed in the Data Access (DAO) object library in the Object Browser.

Remarks

The EditMode property is most useful when you want to depart from the default functionality of a Data control or if you aren't using a Data control with Visual Basic Professional Edition.  You can check the value of the EditMode property and the value of the action parameter in the Validate event procedure to determine whether to invoke the Update method.

You can also check to see if the LockEdits property setting is True and the EditMode property setting is dbEditInProgress to determine whether the current data page is locked.


See Also

AddNew Method

CancelUpdate Method

Edit Method

LockEdits Property

Update Method

UpdateRecord Method

Validate Event


EditMode Property Applies To

Data Control

Dynaset-Type Recordset

Table-Type Recordset


EditMode Property Example

This example checks the EditMode property of a Recordset object and completes the update if the AddNew method has been invoked or the object is being edited.

Function PostChange(Rs as Recordset) As Integer

If (Rs.EditMode = dbEditAdd) or  _

(Rs.EditMode = dbEditInProgress) Then

Rs.Update

PostChange = True

Else

PostChange = False

End If

End Function


IniPath Property

See Also	Example	Applies To

Returns or sets the full path and filename of the Microsoft Jet database engine initialization (.INI) file.

Syntax

object.IniPath [= value]

The IniPath property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that points to a user-supplied ASCII file containing Jet engine settings or parameters needed for installable ISAM databases.  (Data type is String.)

Remarks

The Jet engine can be configured with a user-provided initialization file.  You can use the initialization file settings to set options, such as page timeout and maximum buffer size.

You also use this file to provide initialization parameters for some installable ISAM database drivers.  For example, to use Paradox version 4.0, set the IniPath property to an initialization file containing the appropriate parameters.

Jet engine initialization is handled differently in 16- and 32-bit systems:

16-bit [image] For this option to have any effect, the IniPath property must be set before any other data access functions are invoked by any application in the system.  If the Jet engine is already initialized, a trappable error occurs.  Except for the SystemDB setting, the scope of the .INI file settings is public to the system.  Once set, these settings can't be changed without restarting all programs that are using the Jet engine.  The exception is the SystemDB setting, which can be set differently by each application.

32-bit [image] For this option to have any effect, the IniPath property must be set before any other data access functions are invoked by your application.  If the Jet engine is already initialized, a trappable error occurs.  The scope of this setting is limited to your application and can't be changed without restarting your application.

Earlier versions of Microsoft Access may not use the same version of the Jet engine as Visual Basic version 4.0.  However, other applications using the Jet engine version 2.5/3.0 will initialize the engine.

The IniPath property replaces the outdated SetDataAccessOption parameter DB_OPTIONINIPATH used in Visual Basic version 3.0.


IniPath Property Applies To

DBEngine Object


IniPath Property Example

This example sets the path in the IniPath property to an application .INI file.

Sub SetPathFirst()

DBEngine.IniPath = "C:\MYAPPDIR\MYAPP.INI"

End Sub


See Also

SetDataAccessOption Statement


RecordsAffected Property

See Also	Example	Applies To

Returns the number of records affected by the most recently invoked Execute method.

Syntax

object.RecordsAffected

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The RecordsAffected property return value is an integer from 0 to the number of records affected by the most recently invoked Execute method on either a Database or QueryDef object.  (Data type is Long.)

Remarks

RecordsAffected contains the number of records deleted, updated, or inserted when running an action query.  When you use the Execute method to run a QueryDef, the RecordsAffected property setting is the number of records affected.

Note   The RecordsAffected property setting is the same as the value returned by the ExecuteSQL method.


See Also

ExecuteSQL Method

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection


RecordsAffected Property Applies To

Database Object

QueryDef Object


RecordsAffected Property Example

This example prints the number of records updated by an action query.

Dim Db As Database, Results As Long

Set Db = Workspaces(0).OpenDatabase("BIBLIO.MDB")

Db.Execute "Update Titles Set [Year Published] = 1994 " _

& " WHERE Title = 'To Kill an SQL Query' "

Results = Db.RecordsAffected

Debug.Print Results " records were changed."

Db.Close


Description Property (Data Access)

See Also	Example	Applies To

Returns or sets a descriptive string associated with an error.

Syntax

object.Description [= stringexpression]

The Description property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

stringexpression	A string expression containing a description of the error.

Remarks

The Description property comprises a short description of the error.  Display this property to alert the user to an error that you cannot or do not want to handle.


 See Also

Err Object

Error Function

HelpContext, HelpFile Properties (Data Access)

Number Property (Data Access)

Source Property (Data Access)


Description Property (Data Access) Applies To

Error Object


Description Property Example
Description, Number, and Source (Data Access) Properties Example

This example displays the Description, Number, and Source properties of an Error object.

Debug.Print Errors(Count-1).Number

Debug.Print Errors(Count-1).Description

Debug.Print Errors(Count-1).Source


HelpContext, HelpFile Properties (Data Access)

See Also	Example	Applies To

HelpContext [image] returns a context ID, as a String variable, for a topic in a Microsoft Windows Help file.

HelpFile [image] returns a fully qualified path to the Help file.

Remarks

If a Microsoft Windows Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic it identifies.

Note   You should write routines in your application to handle typical errors.  When programming with an object, you can use the Help supplied by the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable.  When writing OLE Automation objects, you should tailor your Help to programmers programming with your object, as well as supply meaningful information to an end user for an unrecoverable error.


 See Also

Description Property (Data Access)

Number Property (Data Access)

Source Property (Data Access)


HelpContext, HelpFile Properties (Data Access) Applies To

Error Object


HelpContext, HelpFile Properties Example
HelpContext, HelpFile Properties (Data Access) Example

This example uses the HelpContext and HelpFile properties of an Error object to start the Microsoft Windows Help system.  By default, the HelpFile property contains the name of the Microsoft Jet database engine error message Help file.

On Error Resume Next	' Suppress errors for demonstration purposes.

Err.Raise 3004    ' Use VBA to generate "Couldn't find database" error.

Msg = "Press F1 or Help to see " & Errors(0).HelpFile & _
" topic for this error"

MsgBox Msg, , "Error: " & Errors(0).Description & Errors(0).HelpFile & _	Errors(0).HelpContext


Container Property (Data Access)

See Also	Example	Applies To

Returns the name of the Container object to which a Document object belongs

Syntax

object.Container

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Container property return value is a String value.


See Also

Container Object, Containers Collection

Document Object, Documents Collection


Container Property (Data Access) Applies To

Document Object


Container Property (Data Access) Example

This example determines the name of the Container object to which a Document object belongs.

Sub Doc_Analyzer(Doc As Document)

Dim ContainerName As String

ContainerName = Doc.Container

Select Case ContainerName

Case "Relations"

...	' Now that you know it's a relation,

...	' you can do relation-specific things

' in this line of code.

Case "Tables"	' TableDef or QueryDef.

...

Case "Databases"

...

Case "Forms"

...

End Select

End Sub


Number Property (Data Access)

See Also	Example	Applies To

Returns a numeric value specifying an error.  Number is the Error object's default property.

Return Values

The returned value is a Long integer representing an error number.

Remarks

Use the Number property to determine the error that occured.  The value of the property corresponds to a unique trap number that corresponds to an errror condition.  For a complete list of all trap numbers and error conditions, see Trappable Data Access Errors


 See Also

Description Property

HelpFile, HelpContext Properties

Source Property


Number Property Applies To

Error Object


Count Property (Data Access)

See Also	Example	Applies To

Returns the number of objects in a collection.

Syntax

object.Count

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The Count property setting is a Long integer.

Remarks

Members of a collection are numbered starting with 0, so loops are always coded starting with the 0 member; for example:

For I = 0 to Workspaces(0).Databases.Count - 1 ... Next I

Note   You can also use the For Each object In collection syntax to enumerate all members of a collection. For example:

Dim MyDb as Database

For Each MyDb In Workspaces(0).Databases

' Iterate through each element.

Debug.Print MyDb.Name

Next

The Count property setting is never Null.  If its value is 0, there are no objects in the collection.


See Also

Append Method

Delete Method

Refresh Method (Data Access)


Count Property (Data Access) Example

This example lists the names and total number of TableDef and QueryDef objects in the specified database. Note the two ways to do this [image] the second technique does not use the Count property.

Dim MyDB As Database, I As Integer, Td as TableDef

Set MyDB = OpenDatabase("MYDB.MDB")

Debug.Print MyDB.TableDefs.Count

For I = 0 To MyDB.QueryDefs.Count - 1

Debug.Print MyDB.QueryDefs(I).Name

Next I

' Or, without reference to the Count property...

For Each Td In MyDb.TableDefs	' Iterate through each element.

Debug.Print Td.Name

Next

Debug.Print MyDB.QueryDefs.Count


 Count Property (Data Access) Applies To

Columns Collection

Containers Collection

Databases Collection

Documents Collection

Errors Collection

Fields Collection

Groups Collection

Indexes Collection

Parameters Collection

Properties Collection

QueryDefs Collection

Recordsets Collection

Relations Collection

SelBookmarks Collection

TableDefs Collection

Users Collection

Workspaces Collection


Source Property (Data Access)

See Also	Example	Applies To

Returns the name of the object or application that originally generated the error.

Syntax

object.Source

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The return value is a string expression representing the object or application that generated the error.

Remarks

The Source property specifies a string expression representing the object that originally generated the error; the expression is usually the object's class name or programmatic ID.  Use Source to provide your users with information when your code is unable to handle an error generated in an accessed object.  For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Error.Number to its error code for that error and sets Source to Excel.Application.  Note that if the error is generated in another object called by Microsoft Excel, Microsoft Excel intercepts the error and sets Error.Number to its own code for Division by zero.  However, it leaves the other Error object properties (including Source) as set by the object that generated the error.  Source always contains the name of the object that originally generated the error [image] your code can try to handle the error according to the error documentation of the object you accessed.  If your error handler fails, you can use the Error object information to describe the error to your user, using Source and the other Error properties to inform the user which object originally caused the error, its description of the error, and so forth.

Note   The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects.  Checking Error after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred.  Thus, you can be sure which object placed the error code in Error.Number, as well as which object originally generated the error (the one specified in Error.Source).


 See Also

Description Property (Data Access)

HelpContext, HelpFile Properties (Data Access)

Number Property (Data Access)

On Error Statement


Source Property (Data Access) Applies To

Error Object


BeginTrans, CommitTrans, Rollback Statements

See Also

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.

Note   The BeginTrans, CommitTrans, and Rollback statements are included for compatibility with earlier versions.  It's recommended that you use the BeginTrans, CommitTrans, and Rollback methods with the Workspace object instead.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.

Syntax

BeginTrans

CommitTrans

Rollback

Remarks

Whether you use one of these statements or their corresponding methods, the effect is the same:  Transactions always apply globally to a Workspace object.  If you include operations on more than one database or recordset within a transaction, Rollback restores all operations on all databases.


See Also

BeginTrans, CommitTrans, Rollback Methods

CreateWorkspace Method

Database Object, Databases Collection

Workspace Object, Workspaces Collection


CompactDatabase Statement

See Also	Example

Copies, compacts, and gives you the option of changing the version number, collating order, and encryption of a closed database.

Note   The CompactDatabase statement is included for compatibility with earlier versions.  It's recommended that you use the CompactDatabase method with the Workspace object instead.  Both the CompactDatabase statement and the CompactDatabase method have identical parts, arguments, and functions.


See Also

CompactDatabase Method


CreateDatabase Function

See Also	Example

Creates a new Microsoft Jet database, saves the database on disk, creates a new Database object, and returns a Database object that is open for exclusive read/write access.

Note   The CreateDatabase function is included for compatibility with earlier versions.  It's recommended that you use the CreateDatabase method with the Workspace object instead.  Both the CreateDatabase function and the CreateDatabase method have identical parts, arguments, and functions.


See Also

CreateDatabase Method


FreeLocks Statement

See Also

Suspends data processing, allowing the database to release locks on record pages.  This makes all data in your local Dynaset objects current in a multiuser environment.

Note   The outdated FreeLocks statement is included for compatibility with earlier versions.  It's recommended that you use the Idle method with the dbFreeLocks constant instead.

Syntax

FreeLocks


See Also

Idle Method

LockEdits Property


RegisterDatabase Statement

See Also	Example

Makes connect information for an ODBC data source name available for use by the OpenDatabase function.

Note   The RegisterDatabase statement is included for compatibility with earlier versions.  It's recommended that you use the RegisterDatabase method with the DBEngine object instead.  Both the RegisterDatabase statement and RegisterDatabase method have identical parts, arguments, and functions.


See Also

OpenDatabase Method

RegisterDatabase Method


RegisterDatabase Statement 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

Attempts to repair a corrupted Microsoft Jet database.

Note   The RepairDatabase statement is included for compatibility with earlier versions.  It's recommended that you use the RepairDatabase method with the DBEngine object instead.  Both the RepairDatabase statement and RepairDatabase method have identical parts, arguments, and functions.


See Also

Close Method

CompactDatabase Statement

RepairDatabase Method


SetDataAccessOption Statement

See Also

Provides a location for the Microsoft Jet database engine initialization file.

Note   The SetDataAccessOption statement is included for compatibility with earlier versions.  It's recommended that you use the IniPath property of the DBEngine object instead.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.


See Also

DBEngine Object

Workspace Object, Workspaces Collection


OpenDatabase Function

See Also

Opens a specified database and returns the value of an object data type for that database.

Note   The OpenDatabase function is included for compatibility with earlier versions.  It's recommended that you use the OpenDatabase method with the Workspace object instead.  For more information, see Converting Code to the Jet Database Engine Version 2.5/3.0.


See Also

DBEngine Object

OpenDatabase Method


SetDefaultWorkspace Statement

See Also

Establishes the user ID and password for protected (security-enabled) Microsoft Jet databases.  If you aren't using a protected database, this statement is ignored.

Note   The SetDefaultWorkspace statement is included for compatibility with earlier versions.  It's recommended that you use the properties of the Workspace object instead.

Syntax

SetDefaultWorkspace username, password

The SetDefaultWorkspace statement syntax 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.

Remarks

If you use protected databases, this statement must be the first statement used when running your application (although you must first set the IniPath property of the DBEngine object).  Using any other data access control, function, or statement establishes a default username of Admin and a zero-length string ("") as a default password.  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 because they can't be changed once established.  See the Workspace object for details on how multiple user names and passwords can be used in your application.

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 produces an error.  The system database must be in the current directory or in the directory specified in your application's initialization (.INI) file.  If you use a Data control and the SetDefaultWorkspace statement, you must use the statement in the Sub Main procedure or in the first Form_Load event procedure.

This statement doesn't change the application's default Workspace.  However, it sets the default Workspace object's properties.

Note   If no SYSTEM.MDW file is available to the Microsoft Jet database engine, your application can't use any of the security features.  For more information, see Activating Security.


 See Also

CreateWorkspace Method

Refresh Method

SetDataAccessOption Statement

Workspace Object, Workspaces Collection


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.

Note   600 series data access error messages have been replaced or made obsolete by the latest version of the Microsoft Jet database engine.

Codes 2420 to 2448

Codes 3000 to 3099

Codes 3100 to 3199

Codes 3200 to 3299

Codes 3300 to 3399

Codes 3400 to 3464

Codes 3608 to 3622

Replication Errors


Trappable Errors 2420 to 2448
Codes 2420 to 2448

See Also

Code	Message
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 (missing operator).
2432	Syntax error (comma).
2433	Syntax error.
2434	Syntax error (missing operator).
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.
2446	Out of memory during calculation.
2447	Invalid use of '.', '!', or '()'.
2448	Can't set value.


Trappable Errors 3000 to 3099
Codes 3000 to 3099

See Also

Code	Message
3000	Reserved error 'Item'; there is no message for this error.
3001	Invalid argument.
3002	Couldn't start session.
3003	Couldn't start transaction; too many transactions already nested.
3005	'Database name' isn't a valid database name.
3006	Database 'name' is exclusively locked.
3007	Can't open library database 'name'.
3008	Table 'name' is exclusively locked.
3009	Couldn't lock table 'name'; currently in use.
3010	Table 'name' already exists.
3011	Couldn't find object 'name'.
3012	Object 'name' already exists.
3013	Couldn't rename installable ISAM file.
3014	Can't open any more tables.
3015	'Index name' isn't an index in this table.
3016	Field won't fit in record.
3017	The size of a field is too long.
3018	Couldn't find field 'name'.
3019	Operation invalid without a current index.
3020	Update or CancelUpdate without AddNew or Edit.
3021	No current record.
3022	Duplicate value in index, primary key, or relationship.  Changes were unsuccessful.
3023	AddNew or Edit already used.
3024	Couldn't find file 'name'.
3025	Can't open any more files.
3026	Not enough space on disk.
3027	Can't update.  Database or object is read-only.
3028	Can't start your application.  The system database is missing or opened exclusively by another user.
3029	Not a valid account name or password.
3030	'Account name' isn't a valid account name.
3031	Not a valid password.
3032	Can't perform this operation.
3033	No permission for 'name'.
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	Can't open a database with a previous version of your application.
3042	Out of MS-DOS file handles.
3043	Disk or network error.
3044	'Path' isn't a valid path.
3045	Couldn't use 'name'; 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	Can't open database 'name'.  It may not be a database that your application recognizes, or the file may be corrupt.
3051	Couldn't open file 'name'.
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 OLE object fields.
3055	Not a valid file name.
3056	Couldn't repair this database.
3057	Operation not supported on attached, or linked, tables.
3058	Index or primary key can't contain a null value.
3059	Operation canceled by user.
3060	Wrong data type for parameter 'parameter'.
3061	Too few parameters. Expected 'number'.
3062	Duplicate output alias 'name'.
3063	Duplicate output destination 'name'.
3064	Can't open action query 'name'.
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	The action query 'name' cannot be used as a row source.
3070	Can't bind name 'name'.
3071	Can't evaluate expression.
3073	Operation must use an updatable query.
3074	Can't repeat table name 'name' in FROM clause.
3075	'Message' in query expression 'expression'.
3076	'Name' in criteria expression.
3077	'Message' in expression.
3078	Couldn't find input table or query 'name'.
3079	Ambiguous field reference 'reference'.
3080	Joined table 'name' not listed in FROM clause.
3081	Can't join more than one table with the same name 'name'.
3082	JOIN operation 'operation' refers to a non-joined table.
3083	Can't use internal report query.
3084	Can't insert data with action query.
3085	Undefined function 'name' 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 not allowed to have more than one Counter or Autonumber field.
3092	Can't use HAVING clause in TRANSFORM statement.
3093	ORDER BY clause 'clause' conflicts with DISTINCT.
3094	ORDER BY clause 'clause' conflicts with GROUP BY clause.
3095	Can't have aggregate function in expression 'expression'.
3096	Can't have aggregate function in WHERE clause 'clause'.
3097	Can't have aggregate function in ORDER BY clause 'clause'.
3098	Can't have aggregate function in GROUP BY clause 'clause'.
3099	Can't have aggregate function in JOIN operation 'operation'.


Trappable Errors 3100 to 3199
Codes 3100 to 3199

See Also

Code	Message
3100	Can't set field 'name' in join key to Null.
3101	There is no record in table 'name' with key matching field(s) 'name'.
3102	Circular reference caused by 'query reference'.
3103	Circular reference caused by alias 'name' in query definition's SELECT list.
3104	Can't specify Fixed Column Heading 'value' in a crosstab query more than once.
3105	Missing destination field name in SELECT INTO statement 'statement'.
3106	Missing destination field name in UPDATE statement 'statement'.
3107	Record(s) can't be added; no Insert Data permission on 'name'.
3108	Record(s) can't be edited; no Update Data permission on 'name'.
3109	Record(s) can't be deleted; no Delete Data permission on 'name'.
3110	Couldn't read definitions; no Read Definitions permission for table or query 'name'.
3111	Couldn't create; no Create permission for table or query 'name'.
3112	Record(s) can't be read; no Read Data permission on 'name'.
3113	Can't update 'field name'; field not updatable.
3114	Can't include Memo or OLE object when you select unique values 'statement'.
3115	Can't have Memo or OLE object in aggregate argument 'statement'.
3116	Can't have Memo or OLE object in criteria 'criteria' for aggregate function.
3117	Can't sort on Memo or OLE object 'clause'.
3118	Can't join on Memo or OLE object 'name'.
3119	Can't group on Memo or OLE object 'clause'.
3120	Can't group on fields selected with '*' 'table name'.
3121	Can't group on fields selected with '*'.
3122	'Name' not part of aggregate function or grouping.
3123	Can't use '*' in crosstab query.
3124	Can't input from internal report query 'name'.
3125	'Name' isn't a valid name.
3126	Invalid bracketing of name 'name'.
3127	INSERT INTO statement contains unknown field name 'field name'.
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.
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.
3143	Syntax error in TRANSFORM statement.
3144	Syntax error in UPDATE statement.
3145	Syntax error in WHERE clause.
3146	ODBC - call failed.
3151	ODBC - connection to 'name' failed.
3154	ODBC - couldn't find DLL 'name'.
3155	ODBC - insert on attached (linked) table failed.
3156	ODBC - delete on attached (linked) table failed.
3157	ODBC - update on attached (linked) table 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 perform operation; data too long for field.
3164	Field can't be updated.
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 the system database file.
3174	Couldn't open table 'MSysGroups' in the system database file.
3175	Date is out of range or is in an invalid format.
3176	Couldn't open file 'name'.
3177	Not a valid table name.
3179	Encountered unexpected end of file.
3180	Couldn't write to file 'name'.
3181	Invalid range.
3182	Invalid file format.
3183	Not enough space on temporary disk.
3184	Couldn't execute query; couldn't find attached, or linked, table.
3185	SELECT INTO remote database tried to produce too many fields.
3186	Couldn't save; currently locked by user 'name' on machine 'name'.
3187	Couldn't read; currently locked by user 'name' on machine 'name'.
3188	Couldn't update; currently locked by another session on this machine.
3189	Table 'name' is exclusively locked by user 'name' on machine 'name'.
3190	Too many fields defined.
3191	Can't define field more than once.
3192	Couldn't find output table 'name'.
3193	No UserName.
3194	No machine name.
3196	Couldn't use 'database name'; 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.


Trappable Errors 3200 to 3299
Codes 3200 to 3299

See Also

Code	Message
3200	Can't delete or change record.  Since related records exist in table 'name', referential integrity rules would be violated.
3201	Can't add or change record.  Referential integrity rules require a related record in table 'name'.
3202	Couldn't save; currently locked by another user.
3203	Can't specify subquery in expression 'expression'.
3204	Database already exists.
3205	Too many crosstab column headers 'value'.
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 XBASE section of initialization setting.
3209	Invalid Stats entry in XBASE section of initialization setting.
3210	Connection string too long.
3211	Couldn't lock table 'name'; currently in use.
3212	Couldn't lock table 'name'; currently in use by user 'name' on machine 'name'.
3213	Invalid Date entry in XBASE section of initialization setting.
3214	Invalid Mark entry in XBASE section of initialization setting.
3215	Too many Btrieve tasks.
3216	Parameter 'name' specified where a table name is required.
3217	Parameter 'name' specified where a database name is required.
3218	Couldn't update; currently locked.
3219	Invalid operation.
3220	Incorrect collating sequence.
3221	Invalid entries in Btrieve section of initialization setting.
3222	Query can't contain a Database parameter.
3223	'Parameter name' isn't a valid parameter name.
3224	Can't read Btrieve data dictionary.
3225	Encountered record locking deadlock while performing Btrieve operation.
3226	Errors encountered while using the Btrieve DLL.
3227	Invalid Century entry in XBASE section of initialization setting.
3228	Invalid collating sequence.
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.
3234	ODBC - remote query timeout expired.
3235	ODBC - data type not supported on server.
3238	ODBC - data out of range.
3239	Too many active users.
3240	Btrieve - missing Btrieve engine.
3241	Btrieve - out of resources.
3242	Invalid reference in SELECT statement.
3243	None of the import field names match fields in the appended table.
3244	Can't import password-protected spreadsheet.
3245	Couldn't parse field names from first row of import table.
3246	Operation not supported in transactions.
3247	ODBC - attached, or linked, table definition has changed.
3248	Invalid NetworkAccess entry in initialization setting
3249	Invalid PageTimeout entry in initialization setting.
3250	Couldn't build key.
3251	Operation is not supported for this type of object.
3252	Can't open form whose underlying query contains a user-defined function that attempts to set or get the form's Recordset Clone property.
3254	ODBC - Can't lock all records.
3256	Index file not found.
3257	Syntax error in WITH OWNERACCESS OPTION declaration.
3258	Query contains ambiguous outer joins.
3259	Invalid field data type.
3260	Couldn't update; currently locked by user 'name' on machine 'name'.
3261	Table 'name' is exclusively locked by user 'name' on machine 'name'.
3262	Couldn't lock table 'name'; currently in use by user 'name' on machine 'name'.
3263	Invalid database object.
3264	No field defined - cannot append Tabledef or Index.
3265	'Name' not found in this collection.
3266	Can't append. Field is part of a Fields collection.
3267	Property can be set only when the field is part of a Recordset object's Fields collection.
3268	Can't set this property once the object is part of a collection.
3269	Can't append. Index is part of an Indexes collection.
3270	Property not found.
3271	Invalid property value.
3272	Object isn't a collection.
3273	Method not applicable for this object.
3274	External table isn't in the expected format.
3275	Unexpected error from external database driver 'error number'.
3276	Invalid database ID.
3277	Can't have more than 10 fields in an index.
3278	Database engine has not been initialized.
3279	Database engine has already been initialized.
3280	Can't delete a field that is part of an index or is needed by the system.
3281	Can't delete this index.  It is either the current index or is used in a relationship.
3282	Can't create field or index in a table that is already defined.
3283	Primary key already exists.
3284	Index already exists.
3285	Invalid index definition.
3286	Format of memo file doesn't match specified external database format.
3287	Can't create index on the given field.
3288	Paradox index is not primary.
3289	Syntax error in CONSTRAINT clause.
3290	Syntax error in CREATE TABLE statement.
3291	Syntax error in CREATE INDEX statement.
3292	Syntax error in field definition.
3293	Syntax error in ALTER TABLE statement.
3294	Syntax error in DROP INDEX statement.
3295	Syntax error in DROP TABLE or DROP INDEX.
3296	Join expression not supported.
3297	Couldn't import table or query.  No records found, or all records contain errors.
3298	There are several tables with that name.  Please specify owner in the format 'owner.table'.
3299	ODBC Specification Conformance Error 'message'.  This error should be reported to the ODBC driver vendor.


Trappable Errors 3300 to 3399
Codes 3300 to 3399

See Also

Code	Message
3300	Can't create a relationship.
3301	Can't perform this operation; features in this version are not available in databases with older formats.
3302	Can't change a rule while the rules for this table are in use.
3303	Can't delete this field.  It's part of one or more relationships.
3304	You must enter a personal identifier (PID) consisting of at least four and no more than 20 characters and digits.
3305	Invalid connection string in pass-through query.
3306	At most one field can be returned from a subquery that doesn't use the EXISTS keyword.
3307	The number of columns in the two selected tables or queries of a union query don't match.
3308	Invalid TOP argument in select query.
3309	Property setting can't be larger than 2 KB.
3310	This property isn't supported for external data sources or for databases created in a previous version.
3311	Property specified already exists.
3312	Validation rules and default values can't be placed on system or attached (linked) tables.
3313	Can't place this validation expression on this field.
3314	Field 'name' can't contain a null value.
3315	Field 'name' can't be a zero-length string.
3316	'Table-level validation text'.
3317	One or more values entered is prohibited by the validation rule 'rule' set for 'name'.
3318	Top not allowed in delete queries.
3319	Syntax error in union query.
3320	'Error' in table-level validation expression.
3321	No database specified in connection string or IN clause.
3322	Crosstab query contains one or more invalid fixed column headings.
3323	The query cannot be used as a row source.
3324	The query is a DDL query and cannot be used as a row source.
3325	Pass-through query with ReturnsRecords property set to True did not return any records.
3326	This Recordset is not updatable.
3334	Can be present only in version 1.0 format.
3336	Btrieve: Invalid IndexDDF option in initialization setting.
3337	Invalid DataCodePage option in initialization setting.
3338	Btrieve: Xtrieve options aren't correct in initialization setting.
3339	Btrieve: Invalid IndexDeleteRenumber option in initialization setting.
3340	Query 'name' is corrupt.
3341	Current field must match join key 'name' on 'one' side of outer join.
3342	Invalid Memo or OLE object in subquery 'name'.
3344	Unknown or invalid reference 'name' in validation expression or default value in table 'name'.
3345	Unknown or invalid field reference 'name'.
3346	Number of query values and destination fields aren't the same.
3349	Numeric field overflow.
3350	Object is invalid for operation.
3351	ORDER BY expression 'expression' uses non-output fields.
3352	No destination field name in INSERT INTO statement 'statement'.
3353	Btrieve: Can't find file FIELD.DDF.
3354	At most one record can be returned by this subquery.
3355	Syntax error in default value.
3356	The database is opened by user 'name' on machine 'name'.
3357	This query is not a properly formed data-definition query.
3358	Can't open Microsoft Jet engine system database.
3359	Pass-through query must contain at least one character.
3360	Query is too complex.
3361	Unions not allowed in a subquery.
3362	Single-row update/delete affected more than one row of an attached (linked) table.  Unique index contains duplicate values.
3364	Can't use Memo or OLE object field 'name' in SELECT clause of a union query.
3365	Can't set this property for remote objects.
3366	Can't append a relation with no fields defined.
3367	Can't append.  Object already in collection.
3368	Relationship must be on the same number of fields with the same data types.
3370	Can't modify the design of table 'name'.  It's in a read-only database.
3371	Can't find table or constraint.
3372	No such index 'name' on table 'name'.
3373	Can't create relationship.  Referenced table 'name' doesn't have a primary key.
3374	The specified fields are not uniquely indexed in table 'name'.
3375	Table 'name' already has an index named 'name'.
3376	Table 'name' doesn't exist.
3377	No such relationship 'name' on table 'name'.
3378	There is already a relationship named 'name' in the current database.
3379	Can't create relationships to enforce referential integrity.  Existing data in table 'name' violates referential integrity rules in table 'name'.
3380	Field 'name' already exists in table 'name'.
3381	There is no field named 'name' in table 'name'.
3382	Size of a field 'name' is too long.
3383	Can't delete field 'name'.  It's part of one or more relationships.
3384	Can't delete a built-in property.
3385	User-defined properties don't support a Null value.
3386	Property 'name' must be set before using this method.
3388	Unknown function 'name' in validation expression or default value on 'name'.
3389	Query support unavailable.
3390	Account name already exists.
3393	Can't perform join, group, or sort.  Combined fields are too long.
3394	Can't save property; property is a schema property.
3396	Can't perform cascading operation.  Since related records exist in table 'name', referential integrity rules would be violated.
3397	Can't perform cascading operation.  There must be a related record in table 'name'.
3398	Can't perform cascading operation.  It would result in a null key in table 'name'.
3399	Can't perform cascading operation.  It would result in a duplicate key in table 'name'.


Trappable Errors 3400 to 3499
Codes 3400 to 3499

See Also

Code	Message
3400	Can't perform cascading operation.  It would result in two updates to field 'name' in table 'name'.
3401	Can't perform cascading operation.  It would cause field 'name' to become null, which is not allowed.
3402	Can't perform cascading operation.  It would cause field 'name' to become a zero-length string, which is not allowed.
3403	Can't perform cascading operation: 'validation text'.
3404	Can't perform cascading operation.  The value entered is prohibited by the validation rule 'rule' set for 'name'.
3405	Error 'error text' in validation rule.
3406	Error 'error text' in default value.
3407	The server's MSysConf table exists, but is in an incorrect format.  Contact your system administrator.
3409	Invalid field name 'name' in definition of index or relationship.
3410	Can't open this database for update.
3411	Invalid entry.  Can't perform cascading operation in table 'name' because value entered is too big for field 'name'.
3413	Can't perform cascading update on table 'name' because it is currently in use by user 'name' on machine 'name'.
3414	Can't perform cascading update on table 'name' because it is currently in use.
3415	Zero-length string is valid only in a text or Memo field.
3416	'reserved error alert'.
3417	An action query cannot be used as a row source.
3417	Can't have action query as an input.
3418	Can't open 'tablename'.  Another user has the table open using a different network control file or locking style.
3419	Can't open this Paradox 4.x or 5.x table because ParadoxNetStyle is set to 3.x in the initialization setting.
3420	Object is invalid or not set.
3421	Data type conversion error.
3422	Can't modify table structure.  Another user has the table open.
3423	You cannot use ODBC to import from, export to, or link an external Microsoft Access or ISAM database table to your database.
3424	Can't create database because Locale is invalid.
3428	The Microsoft Jet database engine has found a problem in your database.  To correct the problem, you must repair and compact the database.
3429	Incompatible installable ISAM version.
3430	While loading the Excel installable ISAM, OLE was unable to initialize.
3431	This is not an Excel 5 file.
3432	Error opening an Excel 5 file.
3433	Invalid parameter in [Excel ISAM] section of the initialization setting.
3434	Can't expand named range.
3435	Cannot delete Excel cells.
3436	Failure creating file.
3437	Excel spreadsheet is full.
3438	The data being exported does not match the format described in the SCHEMA.INI file.
3439	You attempted to attach or import a Microsoft Word mail merge file.  Although you can export such files, you cannot attach or import them.
3440	An attempt was made to import or attach to an empty text file.  To import or attach a text file, the file must contain data.
3441	Text file specification field seperator matches decimal separator or text delimiter.
3442	In the text file specification 'name', the 'name' option is invalid.
3443	In the fixed-width specification 'name', the 'name' does not specify a width.
3444	The fixed-width specification 'name' contains no column widths.
3445	Incorrect version of Jet DLL file was found.
3446	Jet VBA file not found.
3447	The Jet VBA file failed to initialize when called.
3448	OLE system function call failed.
3449	No country code found in connect string for an attached (or linked) table.
3464	Data type mismatch in criteria expression.


Trappable Errors 3608 to 3622
Codes 3608 to 3622

See Also

Code	Message
3608	Record length too long for an indexed Paradox table.
3609	No unique index found for referenced field of primary table.
3610	Same table referenced as both source and destination in make-table query.
3611	Can't execute data definition statements on attached data sources.
3612	Multi-level GROUP BY clause not allowed in a subquery.
3613	Can't create a relationship on attached (or linked) SQL tables.
3614	GUID not allowed in Find method criteria expression.
3615	Type mismatch in JOIN expression.
3616	Updating data in an attached (or linked) table is not supported by this ISAM.
3617	Deleting data in an attached (or linked) table is not supported by this ISAM.
3620	The connection for viewing your attached Excel worksheet was lost.
3621	No country code found in connect string for an attached (or linked) table.
3622	No country code found in connect string for an attached (or linked) table.


Replication Errors

See Also

Code	Message
3452	You cannot make changes to the design of the database at this replica.
3453	You cannot establish or maintain a relationship to a replicable table during this operation.
3455	Cannot make the 'name' object replicable.
3456	Cannot make the 'name' object in 'name' container replicable.
3457	You cannot set the KeepLocal property for an object that is already replicable.
3458	The KeepLocal property cannot be set on a database; it can be set only on the objects in a database.
3459	Once a database has been made replicable, it cannot be made unreplicable.
3460	The operation you attempted conflicts with an existing operation involving the replica.
3461	The replication property you are attempting to set or delete is read-only and cannot be changed.
3463	Cannot find the .dll 'name'.
3465	The disk drive you are attempting to access is unreadable.
3472	Disk full for path 'name'.
3485	The object cannot be made replicable because the database is not replicable.
3486	You cannot add a second ReplicationID Autonumber field to a table.
3487	The database you are attempting to make replicable cannot be converted.
3488	The value specified is not a ReplicaID for any replica in the replica set.
3489	The object specified is not replicable because it is missing a necessary resource.
3490	Cannot make a new replica because the 'name' object in 'name' container could not be made replicable.
3491	The database must be opened in exclusive mode before it can be made replicable.
3492	The synchronization failed because a design change could not be applied to one of the replicas.
3499	Can't retrieve the full path information for a replica.
3510	The replica you are attempting to exchange with is currently being used in another exchange.
3515	The Microsoft Jet database engine could not read the system clock on your computer.
3520	The replica name or ID does not match a currently managed replica.
3521	The two replicas cannot be synchronized because there is no common point to start the synchronization.
3526	The name selected for the system object is already in use.
3531	The wait period for an event has timed-out.
3533	The system object used by a process still exists after the process has stopped.
3545	The two replicas you are attempting to synchronize are from different replica sets.
3546	The type of exchange you are attempting is not valid.
3548	GUIDs do not match or the requested GUID could not be found.
3549	The filename you provided is too long.
3550	There is no index on the GUID column.
3552	The size of the registry parameter exceeds the maximum allowed.
3553	The GUID could not be created.
3555	All valid nicknames for replicas are already in use.
3559	Failure to write because destination disk is full.
3560	The two replicas you are attempting to synchronize have the same ReplicaID.
3561	The two replicas you are attempting to synchronize both have design-master status.
3566	Network IO error.
3569	The replica has been logically removed from the replica set and is no longer available.
3572	A disk IO error occurred while reading or writing to the TEMP directory.
3574	The ReplicaID for this replica was reassigned during a move or copy procedure
3575	The disk drive you are attempting to write to is full.
3576	The database you are attempting to open is already in use by another application.
3577	Can't update replication system column.
3584	Insufficient memory to complete operation.
3592	You cannot make a password-protected database replicable or set password protection on a replicable database.
3593	Can't change a replicable database from allowing multiple data masters to allowing only a single data master.
3594	Can't change a replicable database from allowing only a single data master to allowing multiple data masters.
3595	The system tables in your replica are no longer reliable and the replica should not be used.
3605	Synchronizing with a non-replicated database is not allowed. The 'name' database is not replicable.
3607	The replication property you are attempting to delete is read-only and cannot be removed.
3623	Can't open replication system table 'name' because table is already in use.


See Also

Data Access

Error Function

Error Object, Errors Collection

Error Statement

On Error Statement

Resume Statement

Visual Basic Trappable Errors

Visual Basic Help


Data Control

See Also	Properties	Methods	Events

Provides access to data stored in databases using any one of three types of Recordset objects.  The Data control enables you to move from record to record and to display and manipulate data from the records in bound controls.  Without a Data control, data-aware (bound) controls on a form can't automatically access data.

Syntax

Data

Remarks

You can perform most data access operations using the Data control without writing any code at all.  Data-aware controls bound to a Data control automatically display data from one or more fields for the current record or, in some cases, for a set of records on either side of the current record.  The Data control performs all operations on the current record.

If the Data control is instructed to move to a different record, all bound controls automatically pass any changes to the Data control to be saved in the database.  The Data control then moves to the requested record and passes back data from the current record to the bound controls where it's displayed.

The Data control automatically handles a number of contingencies including empty recordsets, adding new records, editing and updating existing records, and handling some types of errors.  However, in more sophisticated applications, you need to trap some error conditions that the Data control can't handle.  For example, if the Microsoft Jet database engine has a problem accessing the database file, doesn't have permission, or can't execute the query as coded, a trappable error results.  If the error occurs before your application procedures start or due to some internal errors, the Error event is triggered.

Bound Controls

The DBList, DBCombo, and DBGrid controls are all capable of managing sets of records when bound to a Data control.  All of these controls permit several records to be displayed or manipulated at once.

The CheckBox, TextBox, Label, Picture, Image, ListBox and ComboBox controls are also data-aware and can be bound to a single field of a Recordset managed by the Data control.  Additional data-aware controls like the MaskedEdit and 3DCheckBox controls are available in the Professional Edition and from third-party vendors.

Operation

Once the application begins, Visual Basic uses Data control properties to open the selected database, create a Database object and create a Recordset object.  The Data control's Database and Recordset properties refer to the newly created Database and Recordset objects which may be manipulated independently of the Data control [image] with or without bound controls.

When Visual Basic uses the Jet database engine to create a Recordset, no other Visual Basic operations or events can occur until the operation is complete.  However, other Windows-based applications are permitted to continue executing while the Recordset is being created. If the user presses CTRL+BREAK while the Jet engine is building a Recordset, the operation is terminated, a trappable error results, and the Recordset property of the Data control is set to Nothing.  In design time, a second CTRL+BREAK causes Visual Basic to display the Debug window.

When you use a Data control to create a Recordset object or when you create a Recordset object in code and assign it to the Data control, the Microsoft Jet database engine automatically populates the Recordset object.  As a result, bookmarks (and for snapshot-type Recordset objects, recordset data) are saved in local memory; the user doesn't need to manipulate the Data control, and you don't need to invoke the MoveLast method in code.  Page locks used to create the Recordset are released more quickly, making it possible for other Recordset objects to access the same data.  Recordset objects created in code but not assigned to the Data control aren't automatically populated by the Jet engine.  Populate these objects through code.

You can manipulate the Data control with the mouse, moving from record to record or to the beginning or end of the Recordset.  The Data control doesn't permit the user to move off either end of the Recordset using the mouse.  You can't set focus to the Data control.

Validation

Use the Validate event and the DataChanged property to perform last minute checks on the records being written to the database.

Data Access Objects

You can use the Database and Recordset data access objects created by the Data control in your procedures.  The Database and Recordset objects each have properties and methods of their own, and you can write procedures that use these properties and methods to manipulate your data.

For example, the MoveNext method of a Recordset object moves the current record to the next record in the Recordset.  To invoke this method, you could use this code:

Data1.Recordset.MoveNext

The Data control is capable of accessing any of the three types of Jet engine Version 2.0 Recordset objects.  If you don't select a recordset type, a dynaset-type Recordset is created.

Note   The constants used to request a specific Recordset type when using the Data control are different than the constants used to determine the type of Recordset created or to create a Recordset using the OpenRecordset method.

To select a specific type of Recordset, set the Data control's RecordsetType property to:

Recordset Type	Value	Constant

Table	0	vbRSTypeTable

Dynaset	1	(Default) vbRSTypeDynaset

Snapshot	2	vbRSTypeSnapshot

Important   In Visual Basic version 4.0, the Data control no longer creates or accesses Dynaset objects.  For this reason, some of the methods of the Dynaset object are not supported when used with the Recordset object created with the Data control.  For example, the ListFields, ListIndex, CreateDynaset and CreateSnapshot methods are not supported.  All of the remaining methods and properties of the Dynaset object are supported by the dynaset-type Recordset object.  Note that in some cases, properties that are valid when used with a Dynaset object are not valid with all types of Recordset objects that could be created by the Data control.  For example, the Sort property is valid on a Dynaset and on the dynaset-type Recordset, but not valid on a table-type Recordset.

Important   The Data control cannot be used to access Recordset objects created with the dbForwardOnly option bit set.

Professional Edition

As far as data access is concerned, the primary difference between the Standard and Professional Editions of Visual Basic is the ability to create new data access objects.  In the Standard Edition, you can't declare (with the Dim keyword) variables as data access objects in code.  This means that only the Data control can create Database and Recordset objects.

In Visual Basic version 4.0 Professional Edition, you can create a new Recordset object and assign it to the Data control's Recordset property.  Any bound controls connected to the Data control permit manipulation of the records in the Recordset you created.  Make sure that your bound controls' DataField properties are set to field names that are valid in the new Recordset.

Stored Queries

Another important option when using the Data control is the ability to execute stored queries.  If you create a QueryDef object beforehand, the Data control can execute it and create a Recordset using the QueryDef object's stored SQL, Connect and other properties.  To execute a QueryDef, set the Data control's RecordSource property to the QueryDef name and use the Refresh method.

If the stored QueryDef contains parameters, you need to create the Recordset and pass it to the Data control.

BOF/EOF Handling

The Data control can also manage what happens when you encounter a Recordset with no records.  By changing the EOFAction property, you can program the Data control to enter AddNew mode automatically.

You can program the Data control to automatically snap to the top or bottom of its parent form by using the Align property.  In either case, the Data control is resized horizontally to fill the width of its parent form whenever the parent form is resized.  This property allows a Data control to be placed on an MDI form without requiring an enclosing Picture control.


See Also

Align Property

Binding a Control to a Data Control

BOFAction, EOFAction Properties

Bound Data Controls

Data Access Overview

Opening a Database with the Data Control

Retrieving Data Using SQL

Using Parameter Queries with the Data Control


Data Control Properties

Align Property

Appearance Property

BackColor, ForeColor Properties

BOFAction, EOFAction Properties

Caption Property

Connect Property

Database Property

DatabaseName Property

DragIcon Property

DragMode Property

EditMode Property

Enabled Property

Exclusive Property

Font Property

FontBold, FontItalic, FontStrikethru, FontUnderline Properties

FontName Property

FontSize Property

Height, Width Properties

Index Property

Left, Top Properties

MouseIcon Property

MousePointer Property

Name Property

Options Property

ReadOnly Property

Recordset Property

RecordsetType Property

RecordSource Property

Tag Property

Visible Property

WhatsThisHelpID Property


Data Control Methods

Drag Method

Move Method

Refresh Method

ShowWhatsThis Method

UpdateControls Method

UpdateRecord Method

ZOrder Method


Data Control Events

DragDrop Event

DragOver Event

Error Event

MouseDown, MouseUp Events

MouseMove Event

Reposition Event

Resize Event

Validate Event


DBCombo Control

See Also	Properties	Methods	Events

Automatically fills a list box with a field from one Data control and, optionally, passes data to the selected field of a second Data control.  The selected field is copied to a text box combined with the control that may be used to edit the selected field.

Syntax

DBCombo

Remarks

The DBList and DBCombo controls are different from the standard ListBox and ComboBox controls in that they are automatically filled from a Recordset instead of through use of the AddItem method.  In addition, both controls support an automated search mode that can quickly locate items in the list without additional code.

Shown below is a list of the properties used to fill and manage the list, and permit binding of the selected data to a data control.

Property	Specifies

DataSource	Name of Data control that is updated once a selection is made.

DataField	Name of Field object to be updated in Recordset specified by DataSource.

RowSource	Name of Data control used as a source of items for the list portion of the control.

ListField 	Name of Field object in Recordset specified by RowSource to be used to fill the list.  Usually a description field as opposed to a coded field. For example StateName instead of StateID.

BoundColumn	Name of Field object in Recordset specified by RowSource to be passed back to the DataField once a selection is made.

BoundText	Text value of BoundColumn field.  After a selection is made, this value is passed back to the DataSource to update the DataField field.

Text	Text value of the selected item in the list.

MatchEntry	How the list is searched.

SelectedItem	The bookmark of the selected item in the Recordset specified by RowSource property.

VisibleCount	The number of items visible in the list (fully or partially).

VisibleItems	An array of bookmarks [image] one for each item visible in the list.

The DBCombo control permits users to provide a value in the text box portion of the control.  Once entered, this value is located in the list and the current list item is set to that item.  If the item is not found, the BoundText is set to null.

Note   If you do not make the boundary of the control large enough for at least one row of the dropdown list, the list will not appear at run time.


See Also

ComboBox Control

DBGrid Control

DBList Control

Implementing the DBList and DBCombo Controls

ListBox Control

Recordset Object, Recordsets Collection

UpdateRecord Method


DBCombo Properties

Appearance Property

BackColor Property

BoundColumn Property

BoundText Property

Container Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

ForeColor Property

Height Property

HelpContextID Property

Index Property

IntegralHeight Property

Left, Top Properties

ListField Property

Locked Property

MatchedWithList Property

MatchEntry Property

MouseIcon Property

MousePointer Property

Name Property

Object Property

Parent Property

RowSource Property

SelectedItem Property

SelLength Property

SelStart Property

SelText Property

Style Property

TabIndex Property

TabStop Property

Tag Property

Text Property

Visible Property

VisibleCount Property

VisibleItems Property

WhatsThisHelpID Property

Width Property


DBCombo Control Methods

Drag Method

Move Method

Refill Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


DBCombo Control Events

Change Event

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


DBList Control

See Also	Properties	Methods	Events

Automatically fills a data-bound list box with a field from one Data control and (optionally) pass a selected field to a second Data control.

Syntax

DBList

Remarks

The DBList and DBCombo controls differ from the standard ListBox and ComboBox controls because they are automatically filled with data from a Recordset object instead of by using the AddItem method. In addition, both DBList and DBCombo support an automated search mode that can quickly locate items in the list without additional code.

Shown below is a list of the properties you use to fill and manage the list, and bind the selected data to a Data control.

Property	Specifies

DataSource	Name of Data control that is updated once a selection is made.

DataField	Name of Field object that is updated in the Recordset specified by DataSource.

RowSource	Name of Data control used as a source of items for the list portion of the control.

ListField 	Name of Field object in the Recordset specified by RowSource that is used to fill the list.  Usually a description field is used, rather than a coded field, for example, StateName instead of StateID.  DBList does not support fields of LongBinary type for the ListField.

BoundColumn	Name of Field object in the Recordset specified by RowSource that is passed back to the DataField once a selection is made. DBList does not support fields of LongBinary type for the BoundColumn.

BoundText	Text value of BoundColumn field.  Once a selection is made, this value is passed back to the DataSource to update the DataField field.

Text 	Text value of the selected item in the list.

MatchEntry	How the list is searched.

SelectedItem	The bookmark of the selected item in the Recordset specified by the RowSource property.

VisibleCount	The number of items visible in the list (fully or partially).

VisibleItems	An array of bookmarks [image] one for each item visible in the list.

DBlist does not support LongBinary Fields, ie.  you cannot have the listfield or boundcolumn as a LongBinary field.  if you do, nothing will display in the list, and the control will do nothing.

Note   If you do not make the boundary of the control large enough for at least one row of the dropdown list, the list will not appear at runtime.


See Also

ComboBox Control

DBCombo Control

DBGrid Control

Implementing the DBList and DBCombo Controls

ListBox Control

Recordset Object, Recordsets Collection

UpdateRecord Method


DBList Control Properties

Appearance Property

BackColor Property

BoundColumn Property

BoundText Property

DataChanged Property

DataField Property

DataSource Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

ForeColor Property

Height Property

HelpContextID Property

Index Property

IntegralHeight Property

Left, Top Properties

ListField Property

Locked Property

MatchedWithList Property

MatchEntry Property

MouseIcon Property

MousePointer Property

Name Property

Parent Property

RowSource Property

SelectedItem Property

TabIndex Property

TabStop Property

Tag Property

Text Property

Visible Property

VisibleCount Property

VisibleItems Property

WhatsThisHelpID Property

Width Property


DBList Control Methods

Drag Method

Move Method

Refill Method

Refresh Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


DBList Control Events

Click Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event


DBGrid Control

See Also	Properties	Methods	Events

Displays and enables data manipulation of a series of rows and columns representing records and fields from a Recordset object.

Syntax

DBGrid

Remarks

Note   Before you can use the Apex data bound grid control, you need to add the control to the project using the Add Custom Controls dialog box and register the Data Access Object (DAO) library using the Add References dialog box.  Both of these settings can be saved in your AUTOLOAD.MAK file.

The data-aware DBGrid control appears similar to the Grid control; however, you can set the DBGrid control's DataSource property to a Data control so that the control is automatically filled and its column headers set automatically from a Data control's Recordset object.  The DBGrid control is really a fixed collection of columns, each with an indeterminate number of rows.

Each cell of a DBGrid control can hold either text or picture values, but not linked or embedded objects.  You can specify the current cell in code, or the user can change it at run time using the mouse or the arrow keys.  Cells can be edited interactively, by typing into the cell, or programatically.  Cells can be selected individually or by row.

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 object's Width property and/or the DBGrid control's RowHeight property.  At design time, you can change the column width interactively by resizing the column or by changing the column's width in the Column object's property page.

Use the DBGrid control's Columns collection's Count property and the Recordset object's RecordCount property to determine the number of columns and rows in the control.  A DBGrid control can have as many rows as the system resources can support and about 1700 columns.

When you select a cell, the ColIndex property is set, thus selecting one of the Column objects in the DBGrid object's Columns collection.  The Text and Value properties of the Column object reference the contents of the current cell.  The data in the current row can be accessed using the Bookmark property, which provides access to the underlying Recordset object's record.  Each column of the DBGrid control has its own font, border, word wrap, color and other attributes that can be set without regard to other columns.  At design time, you can set the column width and row height and establish columns that are not visible to the user.  You can also prevent users from changing the formatting at run time.

Note   The DBGrid control and the Visual Basic version 3.0 Grid control can't be substituted for each other.


See Also

Bookmark Property

Column Object, Columns Collection

Data Control

Grid Control

Recordset Object, Recordsets Collection

RowHeight Property

RowSource Property

SelBookmarks Collection


DBGrid Control Properties

Align Property

AllowAddNew Property

AllowDelete Property

AllowRowSizing Property

AllowUpdate Property

BackColor Property

Bookmark Property

BorderStyle Property

Caption Property

ColumnHeaders Property

Columns Property

Container Property

DataMode Property

DataSource Property

DefColWidth Property

DragIcon Property

DragMode Property

Enabled Property

Font Property

ForeColor Property

HeadFont Property

HeadLines Property

Height Property

HelpContextID Property

Index Property

Left Property

LeftCol Property

Name Property

Negotiate Property

Object Property

Parent Property

RecordSelectors Property

RowDividerStyle Property

RowHeight Property

ScrollBars Property

SelBookmarks Property

SelEndCol Property

SelStartCol Property

TabIndex Property

TabStop Property

Tag Property

Top Property

TopRow Property

Visible Property

VisibleCols Property

VisibleCount Property

VisibleItems Property

VisibleRows Property

WhatsThisHelpID Property

Width Property


DBGrid Control Methods

ColContaining Method

Drag Method

GetBookmark Method

Move Method

Rebind Method

Refresh Method

RowBookmark Method

RowContaining Method

RowTop Method

Scroll Method

SetFocus Method

ShowWhatsThis Method

ZOrder Method


DBGrid Control Events

AfterColUpdate Event

AfterDelete Event

AfterInsert Event

AfterUpdate Event

BeforeColUpdate Event

BeforeDelete Event

BeforeInsert Event

BeforeUpdate Event

Change Event

Click Event

ColResize Event

DblClick Event

DragDrop Event

DragOver Event

GotFocus Event

HeadClick Event

KeyDown Event

KeyPress Event

KeyUp Event

LostFocus Event

MouseDown Event

MouseMove Event

MouseUp Event

RowColChange Event

RowLoaded Event

RowResize Event

Scroll Event

SelChange Event

UnboundAddData Event

UnboundDeleteRow Event

UnboundReadData Event

UnboundWriteData Event


SelBookmarks Collection

See Also	Properties	Methods

A SelBookmarks collection contains a bookmark for each row selected in a DBGrid control.

Syntax

SelBookmarks

Remarks

Use the SelBookmarks property of the DBGrid control to return the SelBookmarks collection.  Bookmarks are added to the SelBookmarks collection in the order they're selected.  You can reposition the DBGrid control's current record pointer by setting the Bookmark property to one of the selected bookmarks in the SelBookmarks collection.

Use the Add method to add bookmarks to the SelBookmarks collection.  Once a bookmark is appended to the SelBookmarks collection, it appears selected in the DBGrid control.

To remove a bookmark from the SelBookmarks collection, use the Remove method.  Once a bookmark is removed from the SelBookmarks collection, it no longer appears selected in the DBGrid control.

The SelBookmarks collection supports the Add and Remove methods as well as the Count property.  Using these methods and properties, you can manipulate the list of selected items in the DBGrid control.  For example, you can programmatically select additional items by using the Add method, or determine the total number of selected items using the Count property.


See Also

Bookmark Property

Column Object, Columns Collection

DBGrid Control

GetBookmark Method

RowBookmark Method

SelChange Event

SelBookmarks Property

SelEndCol, SelStartCol Properties


SelBookmarks Methods

Add Method (DBGrid)

Item Method

Remove Method


SelBookmarks Properties

Count Property


Column Object, Columns Collection

See Also	Properties	Methods

Column object [image] represents a column within a DBGrid control.

Columns collection [image] contains all stored Column objects of a DBGrid control.

Syntax

Column

Columns

Remarks

You manipulate a column using a Column object and its methods and properties.  For example, you can:

Get the number of columns in the DBGrid control using the Count property.

Add a column to the DBGrid control by using the Add method of the Columns collection.

Remove a column from the DBGrid control by using the Remove method of the Columns collection.

Read or set the Value property of a Column.

Determine the currently selected Column object using the ColIndex property of the DBGrid control.


See Also

DBGrid Control


Column Object, Columns Collection Properties

Legend

Alignment Property

AllowSizing Property

BackColor, ForeColor Properties

Caption Property

ColIndex Property

Count Property

DataField Property

DefaultValue Property

DividerStyle Property

Font Property

HeadBackColor Property

HeadForeColor Property

Height, Width Properties

Left, Top Properties

Locked Property

NumberFormat Property

ScrollBars Property

Text Property

Value Property

Visible Property


Column Object, Columns Collection Methods

Legend

Add Method (DBGrid)

CellText Method

CellValue Method

Item Method

Remove Method


Error Event

See Also	Example	Applies To

Occurs only as the result of a data access error that takes place when no Visual Basic code is being executed.

Syntax

Private Sub object_Error ([index As Integer,] dataerr As Integer, response As Integer)

The Error event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	Identifies the control if it's in a control array

dataerr	The error number.

response	A number corresponding to the response you want to take, as described in Settings.

Settings

The settings for response are:

Constant	Value	Description

vbDataErrContinue	0	Continue.

vbDataErrDisplay	1	(Default) Display the error message.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

You usually provide error-handling functionality for run-time errors in your code.  However, run-time errors can occur when none of your code is running, as when:

A user clicks a Data control button.

The Data control automatically opens a database and loads a Recordset object 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.

If you don't code an event procedure for the Error event, Visual Basic displays the message associated with the error.


Error Event Applies To

Data Control


See Also

AddNew Method

Data Access Overview

Data Control

Delete Method

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection

Trappable Data Access Errors


Error Event Example

This example displays an Open dialog box if the database specified in the Data control's DatabaseName property isn't found.

Private 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 box.

...

End Select

End Sub


Reposition Event

See Also	Example	Applies To

Occurs after a record becomes the current record.

Syntax

Private Sub object.Reposition ([index As Integer])

The Reposition event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	Identifies the control if it's in a control array

Remarks

When a Data control is loaded, the first record in the Recordset object becomes 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 one of the Move methods, such as MoveNext, the Find methods, such as FindFirst, or any other property or method that changes the current record, 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.


Reposition Event Applies To

Data Control


See Also

AbsolutePosition Property

Data Access Overview

DataChanged Property

Error Event

FindFirst, FindLast, FindNext, FindPrevious Methods

Move Method

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

PercentPosition Property

Recordset Object, Recordsets Collection

Validate Event


Reposition Event Example

This example changes the selection of a ListBox control based on data in the current record.

' In the Declarations section.

Dim Loading As Integer

Private Sub Form_Load ()

Data1.DatabaseName = "C:\VB\BIBLIO.MDB"

Data1.RecordSource = "SELECT DISTINCT State FROM Publishers"

Loading = True	' Set the global variable.

' Open database and recordset.

Data1.Refresh

Do While Not Data1.Recordset.EOF

If Not IsNull(Data1.Recordset(0)) Then	' If not empty,

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

Private 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


Validate Event

See Also	Example	Applies To

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

Private Sub object_Validate ([ index As Integer,] action As Integer, save As Integer)

The Validate event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	Identifies the control if it's in a control array

action	An integer that indicates the operation causing this event to occur, as described in Settings.

save	A Boolean expression specifying whether bound data has changed, as described in Settings.

Settings

The settings for action are:

Constant	Value	Description

vbDataActionCancel	0	Cancel the operation when the Sub exits.

vbDataActionMoveFirst	1	MoveFirst method.

vbDataActionMovePrevious	2	MovePrevious method.

vbDataActionMoveNext	3	MoveNext method.

vbDataActionMoveLast	4	MoveLast method.

vbDataActionAddNew	5	AddNew method.

vbDataActionUpdate	6	Update operation (not UpdateRecord).

vbDataActionDelete	7	Delete method.

vbDataActionFind	8	Find method.

vbDataActionBookmark	9	The Bookmark property has been set.

vbDataActionClose	10	The Close method.

vbDataActionUnload	11	The form is being unloaded.

The settings for save are:

Setting	Description

True	Bound data has changed.

False	Bound data has not changed.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

The save argument initially indicates whether bound data has changed.  This argument 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 set to 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 no bound controls exist.  You can use this event to change values and update data.  You can also choose to save data or stop whatever action is causing the event to occur and substitute a different action.

You can change the action argument to convert one action into another.  You can change the various Move methods and the AddNew method, which can be freely exchanged (any Move into AddNew, any Move into any other Move, or AddNew into any Move).  When using AddNew, 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.

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 can't use any methods (such as MoveNext) on the underlying Recordset object during this event.


Validate Event Applies To

Data Control


See Also

AddNew Method

Bookmark Property

Close Method

Data Access Overview

Data Control

Delete Method

Edit Method

EditMode Property

FindFirst, FindLast, FindNext, FindPrevious Methods

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Recordset Object, Recordsets Collection

Update Method

UpdateRecord Method


AfterColUpdate Event

See Also	Example	Applies To

Occurs after data is moved from a cell in the DBGrid control to the control's copy buffer.

Syntax

Private Sub object_AfterColUpdate ([index As Integer,] colindex As Integer)

The AfterColUpdate event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

colindex	An integer that identifies the column in the control.

Remarks

When a user completes editing within a DBGrid control cell, as when tabbing to another column in the same row, pressing ENTER, or when the control loses focus, the BeforeColUpdate event is executed, and unless canceled, data from the cell is moved to the control's copy buffer.  Once moved, the AfterColUpdate event is executed.

The AfterColUpdate event occurs after the BeforeColUpdate event, and only if the cancel argument in the BeforeColUpdate event is not set to True.

Once the AfterColUpdate event procedure begins, the cell data has already been moved to the control's copy buffer and can't be canceled, but other updates can occur before the data is committed to the Recordset.


See Also

BeforeColUpdate Event

Change Event

ColIndex Property

DBGrid Control

RowColChange Event


AfterColUpdate Event Applies To

DBGrid Control


AfterColUpdate Event Example

This example does a lookup when one column is updated and places the result in another column.

Private Sub DataGrid1_AfterColUpdate (ColIndex As Integer)

If ColIndex = 1 Then

Data1.Recordset.FindFirst "PubId = " _

 & DataGrid1.Columns(1).Value

If Not Data1.Recordset.NoMatch Then

DataGrid1.Columns(2).Value = _

 Data1.Recordset.Fields("Publisher")

Else

DataGrid1.Columns(2).Value = "No Match"

End If

End If

End Sub


AfterDelete Event

See Also	Example	Applies To

Occurs after the user deletes a selected record in the DBGrid control.

Syntax

Private Sub object_AfterDelete ([index As Integer,] colindex As Integer)

The AfterDelete event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

colindex	An integer that identifies the column.

Remarks

When the user selects a record selector in the DBGrid control and presses DEL or CTRL+X, the selected row is deleted.  Before the record is deleted, the BeforeDelete event is triggered.  Once the row is deleted, the AfterDelete event is triggered.  The row selected for deletion is available in the collection provided by the SelBookmarks property.


See Also

BeforeColUpdate Event

BeforeDelete Event

SelBookmarks Property


AfterDelete Event Applies To

DBGrid Control


AfterDelete Event Example

This example displays a message confirming that a record has successfully been deleted.

Private Sub DataGrid1_AfterDelete ()

MsgBox "Record has successfully been deleted!"

End Sub


AfterInsert Event

See Also	Example	Applies To

Occurs after the user inserts a new record into the DBGrid control.

Syntax

Private Sub object_AfterInsert (index As Integer)

The AfterInsert event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

Remarks

When the user selects the new record (at the bottom of the control) and enters a character in one of the cells, the BeforeInsert event is triggered, followed by the BeforeUpdate, AfterUpdate and AfterInsert events.

When the AfterInsert event is triggered, the record has already been added to the database.  The Bookmark property can be used to access the new record.

The AfterInsert event can't be canceled.

The AfterInsert event procedure can be used to update other tables or to perform post-update cleanup of other controls.


See Also

AfterUpdate Event

BeforeInsert Event

BeforeUpdate Event


AfterInsert Event Applies To

DBGrid Control


AfterInsert Event Example

This example creates an entry in a related table if the user enters a value in a column in the grid.

Private SubDataGrid1_AfterInsert ()

If DataGrid1.Columns(1).Value <> "" Then

Data2.Recordset.AddNew

Data2.Recordset.Fields("PubId") = DataGrid1.Columns(1).Value

Data2.Recordset.Update

End If

End Sub


AfterUpdate Event

See Also	Example	Applies To

Occurs after changed data has been written to the database from a DBGrid control.

Syntax

Sub object_AfterUpdate (index As Integer)

The AfterUpdate event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies 00a control if it is in a control array.

Remarks

When the user moves to another row, or the Recordset object's Update method is executed, data is moved from the control's copy buffer to the Data control's copy buffer and written to the database.  Once the write is complete, the AfterUpdate event is triggered.

The updated record is available by using the Bookmark property of the DBGrid control.

The AfterUpdate event occurs after the BeforeUpdate event, but before the LostFocus event for the control (or GotFocus for the next control in the tab order).  This event occurs even if the control isn't bound.  The event can't be canceled, but other updates can occur.

Unlike the Change event, changing data in a control or record using code doesn't trigger this event.


See Also

BeforeColUpdate Event

BeforeInsert Event

BeforeUpdate Event

Change Event

GotFocus Event

LostFocus Event


AfterUpdate Event Applies To

DBGrid Control


AfterUpdate Event Example

This example updates a label when any change has been made in the grid.

Private Sub DataGrid1_AfterUpdate ()

Label1.Caption = "Last modified: " & Format$(Now, "Long Date")

End Sub


BeforeColUpdate Event

See Also	Example	Applies To

Occurs after editing is completed in a cell, but before data is moved from the cell to the DBGrid control's copy buffer.

Syntax

Private Sub object_BeforeColUpdate ([ index As Integer,] colindex As Integer, oldvalue As Variant, cancel As Integer)

The BeforeColUpdate event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

colindex	An integer that identifies the column.

oldvalue	A value that contains the value contained in the cell prior to the change.

cancel	A Boolean expression expression that specifies whether the change occurs, as described in Settings.

Settings

The settings for cancel are:

Setting	Description

True	Cancels the change, restores cell to oldvalue, and restores focus to the control.

False	(Default) Continues with change and permits change of focus.

Remarks

The data specified by the oldvalue argument moves from the cell to the control's copy buffer when a user completes editing within a cell, as when tabbing to another column in the same row, pressing ENTER, or changing focus away from the cell.  Before the data has been moved from the cell into the control's copy buffer, the BeforeColUpdate event is triggered.  This event gives your application an opportunity to check the individual grid cells before they are committed to the control's copy buffer.

If your event procedures set the cancel argument to True, the previous value is restored in the cell and focus remains on the control and the AfterColUpdate event is not triggered.

To restore oldvalue in the cell and permit the user to move focus off of the cell, set cancel to False and set the cell to oldvalue as follows:

Cancel = False

DBGrid1.Columns(ColIndex).Value = OldValue

The AfterColUpdate event occurs after the BeforeColUpdate event.

By setting the cancel argument to True, the user can not move the focus from the control until the application determines that the data can be safely moved back to the control's copy buffer.


See Also

AfterColUpdate Event

AfterUpdate Event

BeforeInsert Event

BeforeUpdate Event

ColIndex Property

DBGrid Control


BeforeColUpdate Event Applies To

DBGrid Control


BeforeColUpdate Event Example

This example checks to make sure that the value the user has typed in is within a certain range; otherwise it disables the update.

Private Sub DataGrid1.BeforeColUpdate (ColIndex As Long, OldValue As Variant, Cancel As Integer)

If ColIndex = 1 Then

If DataGrid1.Columns(1).Value < Now Then

Cancel = True

MsgBox "You must enter a date that is later than today."

End If

End If

End Sub


BeforeDelete Event

See Also	Example	Applies To

Occurs before a selected record is deleted in a DBGrid control.

Syntax

Private Sub object_BeforeDelete ([index As Integer,] cancel As Integer)

The BeforeDelete event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

cancel	A Boolean expression that determines whether a record is deleted, as described in Settings.

Settings

The settings for cancel are:

Setting	Description

True	Leaves focus on control and doesn't delete the record.

False	(Default) Continues with delete operation and enables change of focus.

Remarks

When the user selects a record selector in the control and presses DEL or CTL+X, the BeforeDelete event is triggered before the selected row is deleted.

Once the row is deleted, the AfterDelete event is triggered.  The row selected for deletion is available in the collection provided by the SelBookmarks property.

If your event procedure sets the canceI argument to True, the row isn't deleted.

If more than one row is selected, the error message Multiple rows cannot be deleted is displayed.


See Also

AfterDelete Event

AfterUpdate Event

BeforeInsert Event

BeforeUpdate Event


BeforeDelete Event Applies To

DBGrid Control


BeforeDelete Event Example

This example displays a message that asks the user to confirm a deletion in a grid.

Private Sub DataGrid1_BeforeDelete (Cancel As Integer)

Dim mResult As Integer

mResult = MsgBox("Are you sure that you want to delete " _

 & DataGrid1.SeletedRows &  " record?", _

 vbYesNo And vbQuestion, "Delete Confirmation")

If mResult = vbNo Then Cancel = True

End Sub


BeforeInsert Event

See Also	Example	Applies To

Occurs before new records are inserted into a DBGrid control.

Syntax

Private Sub object_BeforeInsert ([ index As Integer,] cancel As Integer)

The BeforeInsert event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array

cancel	A Boolean expression that determines if a record is added, as described in Settings.

Settings

The settings for cancel are:

Setting	Description

True	Leaves focus on control and doesn't add a new record.

False	(Default) Continues with copy and enables change of focus.

Remarks

When the user selects the new record (at the bottom of the DBGrid control) and enters a character in one of the cells, the BeforeInsert event is triggered, followed by the BeforeUpdate, AfterUpdate and AfterInsert events.

If your event procedure sets the canceI argument to True, the row isn't inserted and the cell is cleared.

When the BeforeInsert is triggered, the record has not been added to the database.  The new record exists in the DBGrid control's copy buffer until this event procedure ends.

After the AfterInsert event is finished, the new record row in the DBGrid control is reinitialized and the edited record becomes the last row in the DBGrid control.


See Also

AfterDelete Event

AfterInsert Event

AfterUpdate Event

BeforeUpdate Event


BeforeInsert Event Applies To

DBGrid Control


BeforeInsert Event Example

This example displays a message that asks the user to confirm the addition of a new record.

Private Sub DataGrid1_BeforeInsert (Cancel As Integer)

Dim mResult As Integer

mResult = MsgBox("Confirm: Add a new record?", _

 vbYesNo And vbQuestion, "Confirmation")

If mResult = vbNo Then Cancel = True

End Sub


BeforeUpdate Event

See Also	Example	Applies To

Occurs before data is moved from a DBGrid control to the control's copy buffer.

Syntax

Private Sub object_BeforeUpdate ([index As Integer,] cancel As Integer)

The BeforeUpdate event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

cancel	A Boolean expression that determines if data is copied, as described in Settings.

Settings

The settings for cancel are:

Setting	Description

True	Leaves focus on control and doesn't copy data.

False	(Default) Continues with copy operation and enables change of focus.

Remarks

When the user moves to another row or the Recordset object's Update method is executed, data is moved from the control's copy buffer to the Data control's copy buffer and written to the database.

Just before the data is moved from the DBGrid control's copy buffer back into the Data control's copy buffer, the BeforeUpdate event is triggered.  Unless the copy operation is canceled, the AfterUpdate event is triggered after the data has been moved back into the Data control's copy buffer and written to the database.  The updated record is available by using the Bookmark property of the DBGrid control.

If you set the BeforeUpdate event cancel argument to True, focus remains on the control, neither the AfterUpdate or LostFocus event is triggered, and the record isn't saved to the database.

The BeforeUpdate event occurs before the AfterUpdate and LostFocus events for this control, or before the GotFocus event for the next control in the tab order.

This event occurs even if the control isn't bound.

Unlike the Change event, changing data in a control or record using code doesn't trigger this event.

You can use this event to validate data in a bound control record before permitting the user to commit the change to the Data control's copy buffer.  By setting the cancel argument to True, the user can't move focus from the control until the application determines whether the data can be safely moved back to the Data control's copy buffer.


See Also

AfterUpdate Event

Change Event

DBCombo Control

DBList Control

GotFocus Event

LostFocus Event


BeforeUpdate Event Applies To

DBGrid Control


BeforeUpdate Event Example

This example displays a message that tells the user to enter a value in the first column before the grid can be updated.

Private Sub DataGrid1_BeforeUpdate (Cancel As Integer)

If DataGrid1.Columns(1).Value = "" Then

MsgBox "You must enter value in the first column!"

Cancel = True

End If

End Sub


ColResize Event

See Also	Example	Applies To

Occurs before the Paint event when a user resizes a column of a DBGrid control.

Syntax

Private Sub object_ColResize ([ index As Integer,] colindex As Integer, cancel As Integer)

The ColResize event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

colindex	An integer that identifies the column.

cancel	A Boolean expression that determines whether a column is resized, as described in Settings.

Settings

The settings for cancel are:

Setting	Description

True	Cancels the change, restores column to its original width, and cancels the pending Paint event.

False	(Default) Continues with width change and subsequent Paint event.

Remarks

When the user resizes a column, the ColResize event is triggered.  Your event procedure can accept the change, alter the degree of change, or cancel the change completely.

If you set the cancel argument to True, the column width is restored and no Paint event is triggered.  To alter the degree of change, set the Column.Width property to the desired value.

Executing the Refresh method within the procedure causes the control to be repainted even if the cancel argument is True.


See Also

ColIndex Property

Paint Event

RowResize Event

Width Property


ColResize Event Applies To

DBGrid Control


ColResize Event Example

This example resizes all the columns to the size of the first column if the user sizes the first column.

Private Sub DataGrid1_ColResize (ColIndex As Integer, Cancel As Integer)

Dim nCol As Column

If ColIndex = 1 Then

For Each nCol In DataGrid1.Columns

nCol.Width = DataGrid.Columns(1).Width

Next

End If

End Sub


HeadClick Event

See Also	Example	Applies To

Occurs when the user clicks on the header for a particular column of a DBGrid control.

Syntax

Private Sub object_HeadClick ([ index As Integer,] colindex As Integer)

The HeadClick event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

colindex	An integer that identifies the column.

Remarks

One possible action for this event is to resort the Recordset object based on the selected column .


See Also

Click Event

ColIndex Property

Recordset Property


HeadClick Event Applies To

DBGrid Control


HeadClick Event Example

This example sorts the record source of the Data control based on which column the user clicked.

Private Sub DataGrid1_HeadClick (ColIndex As Integer)

Data1.RecordSource = "Select * From Publishers Order By " & _

 DataGrid1.Columns(ColIndex).DataField

Data1.Refresh

End Sub


RowLoaded Event

See Also	Applies To

Occurs when the DBGrid control has loaded a row from the database.

Syntax

Private Sub object_RowLoaded ([ index As Integer,] bookmark As String)

The RowLoaded event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

bookmark	A string expression containing a bookmark for the loaded row.

Remarks

Enables your code to fill in default values for unbound fields or perform other operations after the record is loaded.


See Also

DBGrid Control


RowLoaded Event Applies To

DBGrid Control


RowResize Event

See Also	Example	Applies To

Occurs before the Paint event when a user resizes rows in a DBGrid control.

Syntax

Private Sub object_RowResize ([ index As Integer,] cancel As Integer)

The RowResize event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	An integer that identifies a control if it is in a control array.

cancel	A Boolean expression that determines if a change is cancelled, as described in Settings.

Settings

The settings for cancel are:

Setting	Description

True	Cancels the change, restores row to its original height, and cancels the pending Paint event.

False	(Default) Continues with change of row height and subsequent Paint event.

Remarks

The user can resize the DBGrid control rows using the mouse.  When the user changes the height, the RowResize event is triggered.  Your event procedure can accept the change, alter the degree of change, or cancel the change completely.

The DBGrid control's RowHeight property determines the height for all rows in the control.

If you set the cancel argument to True, the row height is restored and no Paint event is fired.  To alter the degree of change, set the RowHeight property to the desired value.

Executing the Refresh method within the procedure causes the control to be repainted even if the cancel argument is True.


See Also

ColWidth Property

Paint Event

RowHeight Property


RowResize Event Applies To

DBGrid Control


RowResize Event Example

This example ensures that there are at least 5 visible rows in the grid.

Private Sub DataGrid1_RowResize (Cancel As Integer)

If DataGrid1.VisibleRows < 5 Then Cancel = True

End Sub


Creating a Database

See Also

This topics discusses how to create a database in code.

A database file can contain a number of data access 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 Tools menu.

External ISAM Databases

An external database is one where the actual data is stored in another file or database management system, not in a Microsoft Jet database (.MDB file).  In most cases, external ISAM databases are stored in a named disk directory.  Thus, to create a new ISAM FoxPro database you would use Windows FileManager or the MkDir statement to create a new directory.  To open this database, specify the path of the directory as the database name.  Individual tables are referenced by their filenames.

External ODBC Databases

The Microsoft Jet database engine can't create external ODBC databases.  This can be accomplished from your application, however, by using the SQL PassThrough option with the Execute method.  For Microsoft SQL Server installations, the system administrator (SA) user can use the OpenDatabase method to open the Master database with the SA password and then pass the required Transact SQL Statements to the SQL Server using the Execute method.  To add tables to the database from Visual Basic, you need to open it directly using a Connect string as discussed below.

Professional Edition

If you have the Professional Edition, you can write code to create and modify the structure of a database.  After you plan the structure of your tables, use these basic steps to create a database:

1.	Use Dim to declare a variable for the Database object you want to create:

Dim DB As Database

2.	Use the Workspace object's CreateDatabase method to create an empty database file and Database.  The CreateDatabase method sets the locale (language) used and the Jet database version.

Note   If you are working with an existing external database, use the CreateDatabase method to set the Database object variable.

Set Db = Workspaces(0).CreateDatabase("MyNewDb",  _

  dbLangGeneral,  _	' General language locale

  dbVersion20)	' Create Jet version 2.0 database

3.	Define each table in the database.  To do this, you first need to define the fields for each table.  Create the database tables and fields using the following steps:

a.	Use the Database object's CreateTableDef method to create a TableDef object for each table.  This method names the database table:

Dim Td as TableDef

Set Td = Db.CreateTableDef("Customer Detail")

b.	Use the new TableDef object's CreateField method to create a Field object for each field.  The example creates and names three fields.  Be sure to set the size property for text fields and any other required attributes before the field is appended:

Dim Fd as Field

Set Fd = Td.CreateField("Cust ID",dbLong)

' This is a counter field.

Fd.Attributes = dbAutoIncrField

Td.Fields.Append Fd

Set Fd = Td.CreateField("Cust Name",dbText,25)

Td.Fields.Append Fd

Set Fd = Td.CreateField("Picture",dbLongBinary)

Td.Fields.Append Fd

c.	Append the new TableDef to the Database object's TableDefs collection.  This is the step that actually creates the object in the database file.  Once appended, you can't make further changes to the appended field.  You may, however, add new fields or delete existing field definitions.

Db.TableDefs.Append Td

4.	You can optionally create one or more Index objects for each table using the TableDef object's CreateIndex method.  After you create each Index, create a Field object to describe which fields are used as keys.  For one of the indexes, set the Primary property to True.  If you want the Jet engine to prevent duplicates in the table based on a chosen index, set the Unique property to True:

a.	Use the TableDef object's CreateIndex method to create an Index object.

Dim Ix as Index

Set Ix = Td.CreateIndex("Customer Index")

b.	Use the Index object's CreateField method to create a Field object for each field in the table that is a component of the key.  Append each Field object to the Index object's Fields collection:

Set Fd = Ix.CreateField("Cust ID")

Fd.Primary = True

Ix.Fields Append Fd

c.	Append each Index object to the Indexes collection of the TableDef with the Append method.  A table can have none or several indexes.

Td.Indexes.Append Ix


See Also

Accessing External Databases

CreateDatabase Method

CreateField Method

CreateIndex Method

CreateTableDef Method

Data Access Overview

Data Control

Dim Statement

Execute Method

Field Object, Fields Collection

Index Object, Indexes Collection

OpenDatabase Method

Required Property

Set Statement

TableDef Object, TableDefs Collection

Unique Property

Using Counter Fields


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).  In any case, you may use an SQL statement to define which records you want, and how you want them ordered and grouped.

If you use an SQL query to retrieve data, the Microsoft Jet database engine only creates a dynaset-type or snapshot-type Recordset.  Once the Recordset is built, you can use one of the Find methods to further refine the search or step through the records one at a time.

There are a variety of ways to execute queries including:

Set the RecordSource property of a Data control and use the Refresh method.

Use an existing Querydef in the Data control's RecordSource property.

Use an SQL action query as an argument to the Execute method.

Create and execute a custom Querydef object.

Use an SQL statement as an argument to the OpenRecordset method.

Execute an existing Querydef with the OpenRecordset method.

Only the first three techniques are available in the Standard Edition.

Using an SQL query with a Data control

1.	Design your SQL query so it returns only the records you want.

2.	Enter the query's SQL statement in the Data control's RecordSource property.  You can do this at design time or run time.  For example, 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 Recordset:

Data1.Refresh

Using an existing QueryDef in the RecordSource property

A Querydef is a database object that doesn't contain data, but it does contain an SQL statement that retrieves data from one or more tables using a specific filter and sort order.  Generally, you can use a Querydef anywhere you can refer to a table.  To retrieve data specified by the Querydef using the Data control:

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 = "MyQuery"

2.	At run time, use the Refresh method to recreate the underlying Recordset in the Data control:

Data1.Refresh

Use an SQL action query as an argument to the Execute method

If you need to execute an action query to perform an operation that doesn't return records, as when you insert or delete records, you can use an SQL statement as an argument to the Execute method.  The Execute method can be used with the Data control or an open Database object as long as the query doesn't return records.  For example, to delete all of the records from a table matching specific criteria, you can use the following code:

Data1.Database.Execute "DELETE FROM Titles " _

& " WHERE [Year Published] = 1869 "

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, Rs as Recordset

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 Recordset with either of these lines of code:

Set Rs = MyQuery.OpenRecordset()
Set Rs = Db.OpenRecordset("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.  Note that the parameter [Name Wanted] isn't enclosed in quotes and is only enclosed in brackets [ ] when the parameter includes imbedded spaces or punctuation:

Dim MyQuery As QueryDef, Db As Database

Dim MySQL As String, Rs As Recordset

Set Db = OpenDatabase("C:\VB\BIBLIO.MDB")

MySQL = "PARAMETERS [Name Wanted] Text;"

MySQL = MySQL & " SELECT Author FROM Authors"

MySQL = MySQL & " WHERE Author = [Name Wanted]"

Set MyQuery = Db.CreateQueryDef("A Name", MySQL)

2.	You must set the parameter before you use the query.  In this case, the author you're searching for is placed in a TextBox control:

MyQuery.Parameters![Name Wanted] = Text1.Text

Set Rs = MyQuery.OpenRecordset()

If Rs.Recordcount > 0 Then 	' The record was found.


See Also

CreateQueryDef Method

Data Access Overview

Data Control

Database Object, Databases Collection

Database Property

Execute Method

FindFirst, FindLast, FindNext, FindPrevious Methods

Name Property

OpenRecordset Method

PARAMETERS Declaration (SQL)

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

RecordSource Property

ReturnsRecords Property

SQL Property


Binding a Control to a Data Control

See Also

A Data control opens a database and creates a Recordset object containing data from the database.  To manipulate this data in controls on your form, you must bind one of the data-aware controls to the Data control.

Once the Data control creates a Recordset, each field in the Recordset can be displayed and modified by binding it to a data-aware bound control.  Set the bound control's DataSource property to the Data control and the DataField property to one of the Recordset object's fields.

The DataSource property can only be set at design time, but you can set or change the DataField property at any time [image] it must, however be set to one of the fields in the bound Recordset.

The TextBox, CheckBox, Image, Label, Picture, ListBox, ComboBox, DBList, DBCombo, and DBGrid controls are all data-aware and can be bound to a Data control.  In addition, Visual Basic Professional Edition and third party vendors provide additional data-aware controls.

To bind a TextBox control 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 down arrow to see a list of the Data controls on the form.  Select the Data control you want or double-click to cycle through the available Data controls.

3.	Select the DataField property and click the down arrow to select one of the available fields in the Recordset created by the Data control.  (If you haven't set the RecordSource property of the Data control, this list is empty.)

To bind a TextBox control to a Data control at run time

1.	You must set the DataSource property of the TextBox control to the name of the Data control (for example, "Data1") at design time.

2.	Set the DatabaseName, RecordSource, and RecordsetType properties of the Data control:

Data1.DatabaseName = "C:\VB\BIBLIO.MDB"	' Set the database.

Data1.RecordSource = "Publishers"	' Set the table or query.

Data1.RecordsetType = dbDynasetType ' Create dynaset-type Recordset.

3.	Set the TextBox control's DataField property to the name of the field in the Data control's Recordset property:

Text1.DataField = "State"	' Bind to State field.


See Also

CheckBox Control

ComboBox Control

Data Access Overview

Data Control

DataField Property

DataSource Property

DBCombo Control

DBGrid Control

DBList Control

Image Control

Label Control

ListBox Control

PictureBox Control

Recordset Property

RecordSource Property

TextBox Control


Opening a Database With the Data Control

See Also

To open a Database object with a Data control, you need to set the following properties and use the Refresh method on the Data control's object.  You can do this in code or interactively using the Properties window at design time.

1.	If you intend to open an installable ISAM like Fox, Excel, dBASE, Paradox or Text, select the database type from the Connect property menu in the Properties window or in code.  When you select the DatabaseName at design time, the filenames displayed are filtered, based on the database type set in the Connect property.

If you need to access an installable ISAM, ODBC or other external database, you must set the Connect property to indicate the type of datasource and any optional parameters needed for that type of database.  For example, for ODBC databases, you need to indicate the type of database (ODBC;) followed by one or more parameters such as UID, PWD and DATABASE.  You can also supply the DSN in the Connect property if it isn't provided in the DatabaseName property.

For installable ISAM databases, you must specify one of the supported database types as shown in the drop-down list in the Data control's Properties window.  See the Connect property for more details.

For best performance against external databases, you should consider attaching external tables to a Microsoft Jet database (.MDB) instead of opening the external database directly.

2.	Set the DatabaseName property with the path and name of the database file or a valid data source name.  When you select a database type in the Connect property, the file dialog box provided by the DatabaseName property from the Properties window includes a filter for the correct filename extension.  You can use this file dialog box to select a valid filename.  For ODBC external databases, you can use the DatabaseName property to specify the Data Source Name (DSN) for the server containing the database to be accessed.

3.	Set the RecordSource property to the name of a Table, QueryDef or view in the database.  You can also enter an SQL statement in the RecordSource property to describe a Recordset.  If the QueryDef contains parameters, you can't use it without first creating a Recordset and passing it to the Recordset property of the Data control.

4.	After valid Connect and DatabaseName properties are provided to the Data control, a list of valid RecordSource values is provided in a drop-down list in the Data  control Properties window.  For example, in the case of Jet databases, this list includes all database Table objects.

5.	Choose the type of Recordset you wish the Data Control to create using the RecordsetType property.

6.	Add one or more bound controls to your current form for each of the Recordset fields that you wish to manipulate.  You don't need to specify a bound control for every field in the Recordset.

7.	Change the DataSource property of each bound control to point to your Data control.  You can bind controls to a Data control only at design time.  Data controls can't be bound to data-aware controls on other forms.

8.	For each bound control, set the DataField property to the Recordset field that this control is to manipulate.  The Properties window queries the database and builds a Recordset to determine the name of each field.  Click the DataField property and choose from the list presented.

9.	If you expect your program to work with empty Recordset objects, you may wish to set the EOFAction properties to respond more appropriately in this case.

10.	To prevent users from scrolling off the end of the Recordset, set the BOFAction property to prevent movement past the beginning of the data.

11.	You may also wish to set the Exclusive, ReadOnly, or Options properties as needed.

12.	If you are accessing a database that has implemented security, you must use the DefaultUser and DefaultPassword properties of the DBEngine object to log on with a valid user name and password before the Jet engine tries to open the Data control's database in the Form_Load event.  The Data control can only access databases from Workspaces(0).  If your user doesn't have permission to access the database, a trappable error results.

Once you set the properties using the Properties window, run your application.  Visual Basic attempts to open your database with the provided parameters.  If you used code to set the Data control properties, use the Data control's Refresh method to open the database.

If the database opens successfully, you can use the Database and Recordset properties of the Data control as Database and Recordset objects.


See Also

Activating Data Access Objects

BOFAction, EOFAction Properties

Choosing a Data Control Recordset Type

Connect Property

CreateWorkspace Method

Database Object, Databases Collection

DatabaseName Property

DataField Property

DataSource Property

DBEngine Object

DefaultUser, DefaultPassword Properties

Exclusive Property

Options Property

Parameter Object, Parameters Collection

Password Property

ReadOnly Property

RecordsetType Property

RecordSource Property

Updatable Property

User Object, Users Collection


Choosing a Data Control Recordset Type

See Also

You can use the Data control to create three types of Recordset objects.  Set the Data control's RecordsetType property to specify the type, as shown in the following table:

Recordset Type	Constant	Suggested Use

Table-type	vbRSTypeTable	Direct read-write access to individual base tables.  Table-type Recordset objects provide the fastest way to access or update data.  Recordset order is determined by Index property of the Recordset object.  For .MDB native tables only [image] not for ODBC or ISAM databases.

Dynaset-type	vbRSTypeDynaset	Keyset-driven read-write access to individual base tables, Querydef objects, or result sets based on SQL queries.  Recordset order is determined by ORDER BY clause in SQL query.  Saves keys in memory.

Snapshot-type	vbRSTypeSnapshot	Data-driven, read-only access to individual base tables, Querydef objects, or result sets based on SQL queries.  Recordset order is determined by ORDER BY clause in SQL query.  Saves data in memory.

Setting the Data control's RecordsetType property indicates a preference for the type of Recordset the Data control creates.  If the Microsoft Jet database engine can't create the type requested, a trappable error occurs.

If you don't specify a recordset type before the Data control creates a Recordset, a dynaset-type Recordset is created, wherever possible.

Note   The Data control doesn't support the outdated Dynaset object.  By default it creates a dynaset-type Recordset that is completely compatible with the Dynaset so any existing code shouldn't have to be modified.

If you create a Recordset without using the Data control (even with another Data control) and set the Recordset property with this new Recordset object, the RecordsetType property of the Data control is set to the Type property of the new Recordset.

Important   The RecordsetType property value doesn't correspond to the value used to identify Recordset object types.  See the OpenRecordset method or the Type property for details.


See Also

Activating Data Access Objects

Data Control

Dynaset-type Recordset

OpenRecordset Method

Recordset Object, Recordsets Collections

Snapshot-type Recordset

Table-type Recordset

Type Property


Activating Data Access Objects

See Also

When you first install Visual Basic, the Microsoft DAO 2.5 Object Library is activated.  This library supports the data access objects (DAO).  However, if you choose not to include the DAO library in your executable, you can deactivate it by using the Add References dialog box from the Tools menu.

Once the DAO library is deactivated, you can't reference any of the DAO objects in code without receiving a compile error message.  (This message usually indicates that there is an undefined user-defined object.)

If you change your AUTOLOAD.MAK file to exclude the DAO library from the list of installed references, you need to manually activate the DAO library using the Add References dialog box before DAO objects can be referenced by code in your application.

In most cases, the DAO library is activated automatically when you use the Data control and bound controls.  To use the .OCX bound controls, however, you must manually activate them.  For example, you must add the Microsoft DBList Controls reference before you execute code in design mode to use the DBList and DBCombo controls.

Once you activate a library or custom control, it remains a part of your project.  When you include activated libraries or controls in your AUTOLOAD.MAK file, these become part of each application you create until you specifically deactivate them.


See Also

Activating Security


Activating Security

See Also

Microsoft Jet databases support a wide variety of security features that can restrict applications from accessing entire databases or their table, field, user, or group objects.  In order to manage which users have permission to access which objects, the Microsoft Jet database engine uses a SYSTEM.MDW file.  This file is created by an application included with Microsoft Access but not with Visual Basic.

Applications written with Visual Basic can access Jet databases created with security enabled, but unless the application has access to the SYSTEM.MDW file, it can't create or modify any security settings.

Note...The file extension .MDW replaces the extension .MDA.

Warning  Because all DBEngine calls within the same process space share the same Jet database engine, there exists a possible security risk if a "trojan horse" in-process OLE server or other DLL were to surreptitiously iterate through the DBEngine.Workspaces collection to find the Workspace used by your application, then loop through the Databases, Recordsets, Tables, and Fields collections to access your data, bypassing security and password protection.  To prevent this possibility, create a Workspace object for your application, but do not append it to the Workspaces collection.  It will then be invisible to any other code.


See Also

Activating Data Access Objects

CreateWorkspace Method


Using Parameter Queries With the Data Control

See Also	Example

If you have a Querydef object that contains a PARAMETERS clause, you need to provide the required parameters to the query before it is executed.  For this reason, you can't provide the name of a parameterized query to the Data control's RecordSource property.  This topic discusses how to fill in the parameters, create a Recordset object and pass it to a Data control.

Unlike Microsoft Access, Visual Basic doesn't prompt you for the parameters when executing parameter queries.  To execute a Querydef, your code needs to:

Fill in the Querydef parameters before executing the query by providing values for each of the members of the Querydef object's Parameters collection.  You may be able to use the Name property of the Parameter object to provide a prompt string.

Open a new Recordset from the modified Querydef using the OpenRecordset method of the Data control's Database object.

Set the Data control's Recordset property to the new Recordset.

Ensure that the DataField properties of the bound controls connected to this Data control are set to the field names returned by the new Recordset.


See Also

Data Control

Parameter Object, Parameters Collection

Querydef Object, QueryDefs Collection

Recordset Object, Recordsets Collection


Using Parameter Queries With the Data Control Example

This example fills in the parameters for a Querydef object named MyParameterQuery stored in the database opened by the Data (Data1) control.  Note the three different syntax options used to pass the arguments to the Parameter object.  The code then builds a Recordset object from the Querydef and subsequently passes it back to the Data control.

The Data control must have created the Database object and the associated QueryDefs collection before it can be referenced.  To accomplish this in the example, one of the tables in the database is referenced in the RecordSource property and the Refresh method is used against the Data control. These two steps are not needed if the Data control has already created a Database object.

Sub RunPQuery()

Dim Qd as Querydef, Rs as Recordset

Data1.RecordSource = "Titles"

Data1.Refresh                    ' Create the Database object

Set Qd = Data1.Database.QueryDefs("MyParameterQuery")

Qd.Parameter(0) = "Redmond"	' City

Qd.Parameter("Enter State") = "WA"	' State

Qd.Parameter!County = "King"	' County

'

'Create a new Recordset from the Query based on the stored QueryDef.

'

Set Rs = Qd.OpenRecordset(Qd,dbOpenDynaset)

'

'Pass the Recordset back to the Data control.

'

Set Data1.Recordset = Rs

End subSub RunPQuery()

Dim Qd as Querydef, Rs as Recordset

Set Qd = Data1.Database.QueryDefs("MyParameterQuery")

Qd.Parameter(0) = "Redmond"	' City

Qd.Parameter("Enter State") = "WA"	' State

Qd.Parameter!County = "King"	' County

'

'Create a new Recordset from the Query.

'

Set Rs = Data1.Database.OpenRecordset(Qd,dbOpenDynaset)

'

'Pass the Recordset back to the Data control.

'

Set Data1.Recordset = Rs

End sub


Data Access Overview

See Also	Objects	Properties	Events	Methods

Visual Basic enables you to access and manipulate data in databases, and to manage databases, their objects and structure.

When creating programs to access databases, you have a variety of development options.  You can use:

The built-in Microsoft Jet database engine with Visual Basic's Data control.

The Jet engine with Visual Basic's data access objects (DAO).

The ODBC API to access any external database with an ODBC driver.

The DB-Library API with the VBSQL custom control to access Microsoft SQL Server.

Third-party custom controls and drivers to access databases.

The Jet Engine

You can use Visual Basic data access objects or the Data control to manipulate databases in either the native Jet engine .MDB format or in other installable ISAM database formats including Fox, dBASE, Excel, Btrieve, Paradox and delimited Text.  In addition, you can use the Jet engine to access Microsoft SQL Server and any other database that can be accessed with an ODBC driver using the same DAO code or the Data control.  The Jet engine version 2.5 is supplied with Visual Basic so you don't need any additional DLLs or drivers.

API-Based Database Interfaces

The VBSQL custom control requires additional declare files, drivers and DLLs that are not included with Visual Basic, but are available separately from Microsoft.  You can use the ODBC API by including ODBC API declare statements in a global module; these are also available from Microsoft.  Both of these API approaches give you a higher degree of control over the external database server.  This can mean higher performance, but can be somewhat more complex to code.  You can't use the Data control or data access objects, but you may be able to fill and manage data-aware bound controls in code using these API techniques.

The Data Control

Using a Data control is the easiest way to create applications that give 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 or may show several records at once.  If the Data control changes to a different record, all bound controls automatically change to display current data.  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.

All Data control operations are executed by the Jet engine so the control is able to open and manipulate any database supported by the Jet engine, including installable ISAM and ODBC database types.

Important   To access any of the programmatic data access objects, the Data control, or any of the data-aware controls, your development environment must have the Microsoft DAO 2.5 Object Library checked in the Add References dialog box.  By default, your AUTOLOAD.MAK file included this library when first installed.  If you don't include this reference, your code may not compile due to User-defined type not defined errors.

Data Access Objects

Both the Standard and Professional Editions of Visual Basic support data access objects (DAO), such as the DBEngine, Workspace, Database, TableDef, Field, Index and Recordset objects.  Although you can't declare (using the Dim keyword) new data access objects with the Standard Edition, you can manipulate those created for you by the Data control.

A Database object contains a number of data access objects, such as TableDef objects that define tables, Field objects that define fields, and so on.  Each object has a set of properties and methods.  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.  When you write code or use the Data control to fetch data from the database, each Recordset object you create is appended to the Recordsets collection.  To manipulate the database data and its structure, you write code that accesses these structured 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.Recordset.Fields("PubID").Value = 99

In addition, like other controls, data access objects have a default collection or 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

Note   Version 4.0 of Visual Basic supports default properties only for the Field, Property and Parameter objects.  For example, the TableDef object no longer supports the Name property as default.  You need to modify your code to include the property wherever needed.

Professional Edition

With the Professional Edition, you can declare new data access object variables for any of the object types using the Dim and Set statements.  For example, the following code creates object variables for a Database, a dynaset-type Recordset, and a Field:

Dim MyDb As Database, MyRs As Recordset, MyFd As Field

Set MyDb = OpenDatabase("BIBLIO.MDB")

Set MyRs = MyDb.OpenRecordset("Authors", dbOpenDynaset)

Set MyFd = MyRs.Fields("Au_ID")

You can use object variables and other DDL features to modify your database structure.  For example, you can add a new Field to an existing table with the following code:

Dim MyDb As Database, MyTd as TableDef, MyFd As Field

Set MyDb = OpenDatabase("BIBLIO.MDB")	' Open database.

Set MyTd = MyDb.TableDefs("Authors")

Set MyFd = MyTd.CreateField("Address", dbText, 20)

MyTd.Fields.Append MyFd	' Append to TableDef fields.

This code creates a New object variable for a Field and 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 for entering data.  In much the same way, you can create new tables and new indexes.

DBEngine and Workspace Objects

All data access objects are derived from the DBEngine object, which represents the Jet engine.  When your application starts, the Jet engine creates a default DBEngine.Workspace object that can be referenced through the Workspaces collection (Workspaces(0)).  You can open additional Workspace objects as needed.  Each Workspace has a user ID and password associated with it.

Note   Unless you need to manipulate databases that have security enabled or create a separate transaction scope, you don't need to reference the DBEngine or Workspace objects.  Visual Basic uses the default DBEngine.Workspaces(0) object if it isn't specifically referenced.  For example, to open a database using DAO and create a table-type Recordset, you can write the following code:

Dim Db as Database, Rs as Recordset

Set Db = OpenDatabase("BIBLIO.MDB")

Set Rs = Db.OpenRecordset("Titles")

All Database objects opened against a Workspace share a common transaction scope.  That is, when you use the BeginTrans method on a database, it applies to all other open databases opened in the Workspace.  In the same way, using the CommitTrans method against one database applies to all other databases opened in the Workspace.

All Database objects created by the Data control are in Workspaces(0).  However, if you create a Recordset object in another Workspace using DAO,  you can manage it using a Data control.

Security

You can restrict access to one or more .MDB databases or their tables using security settings established and managed by the Jet engine.  In your code you can establish Group and User objects to define the scope and level of permissions available to individual users on an object-by-object basis.  For example, you can establish permissions for a specific user so that they have read-only access to one table and full access to another.

Important   Before you can establish or alter any security settings, you need to gain access to the SYSTEM.MDW file associated with the .MDB database.  This file can only be created by a special utility included with Microsoft Access.  Without this file your application can't activate security for a .MDB database.


See Also

Activating Data Access Objects

Activating Security

CreateDatabase Method

CreateField Method

CreateIndex Method

CreateTableDef Method

Data Control

Database Object, Databases Collection

DBEngine Object

Dim Statement

Execute Method

Fields Object, Fields Collection

Index Object, Indexes Collection

OpenDatabase Method

Recordset Object, Recordsets Collection

Required Property

Set Statement

TableDef Object, TableDefs Collection

Type Property

Unique Property

Using Counter Fields

Value property

Workspace Object, Workspaces Collection


Implementing the DBList and DBCombo Controls

See Also

Both the DBList and DBCombo controls are implemented in the same way.  The only differences are the way the data is presented to the user and the presence of the text box portion of the DBCombo control, which is used to enter values.

The DBList and DBCombo controls have two modes that can be used individually or at the same time:

Auto Fill: Automatically fills the list with a selected field from all records managed by the Data control specified by the RowSource property.

Auto Update: Binds the selected record in the control to a specific field in the Recordset object managed by the Data control specified by the DataSource property.

Typically, you use both modes to build a list of items based on a database query.  When an item in the list is selected, it becomes available to the Data control specified by the DataSource property.  The selection also appears in the text box portion of the control where it can be edited.  If the user enters a value in the text box, the list portion of the control attempts to position to a matching item.  If a match is found, the BoundText property value is set, based on the field specified by the BoundColumn property.  If no match is found, the BoundText property is set to Null.

As illustrated above, the DBCombo or DBList controls permit users to select from a list of items and pass that item or some other field from the Recordset specified by the RowSource property to another Data control.

Once the Data control moves to another record, or is otherwise updated, the value from the BoundColumn is passed to the Data control specified by the DataSource property.  If there is no matching item, a Null value is passed to the Data control.  As with all bound controls, the DataField property specifies the field updated in the Recordset managed by the Data control.

For example, you can use the DBCombo (or DBList) control to retrieve and display a list of current suppliers.  You can then use a selection from this list, or enter a new Vendor in the text box portion of the control, to update a VendorID field in a Recordset created from an OrderItem table.  To implement this example, you would:

1.	Add a DBCombo control and two Data controls to your form.

2.	Set the second Data control properties to create a Recordset using the OrderItem table.

3.	Set the first Data control properties to create a snapshot-type Recordset using a ValidSuppliers table.  This control's Visible property should be set to False so the DBCombo (or DBList) control manages the Recordset.

4.	Set the DBCombo object's DataSource property to the second Data control.

5.	Set the DataField property of the DBCombo to the VendorID field.  This binds the DBCombo control to the OrderItem Recordset and specifies that the VendorID field be updated once a selection is made.

6.	Set the RowSource property to the first Data control, which is used to fill the list from the ValidSuppliers Recordset.

7.	Set the ListField property to the Name field.  This specifies which field to use to fill the list portion of the control.  If you use the drop-down list, you can select one of the fields in the Recordset specified by the RowSource property.

8.	Set the BoundColumn property to the Code field.  Note that the BoundColumn property drop-down menu is also derived from the Recordset specified by the RowSource property.  This binds the selected item from the DBCombo control to the  field of the second Data control's Recordset, as specified by the DataField property.  In this case, the DataField property points to the VendorID field, which is updated when the second Data control is updated.

When this program is run, the DBCombo control fills with a list of current vendors drawn from the Recordset specified by the RowSource and ListField properties.  Select one of the OrderItem records using the second Data control.  Next, select one of the valid suppliers from the DBCombo control or change the selected item in the text box portion of the control.  Then reposition the second Data control to a different record and move back to the original record.  Notice that the VendorID field is updated with the VendorID selected from the DBCombo control.  If you supply a value in the text box that isn't in the list, a Null value is used.

As the second Data control moves from record to record with the OrderItem Recordset, the bound field specified by the DataField property is located in the list; that is, the VendorID value read from the database is used to search the list.  If it's found, the item is highlighted in the list, and the Change event of the DBCombo control is triggered.

If the user makes a selection with the DBCombo or DBList control, that value becomes available to the Data control specified by the DataSource property.  The value is subsequently written to the database if the current record is repositioned or an UpdateRecord method is executed.

You can use either the Auto Fill or Auto Update mode alone but, because there is no way to fill these controls without using the RowSource and ListField (or BoundColumn) properties, using the Auto Update mode without the Auto Fill mode may not be particularly useful.  You can't use the AddItem or RemoveItem methods with the DBCombo or DBList controls as you can with the ComboBox control.

You can use the Auto Fill mode by itself.  In this case, the list is filled, and you can add code to the Click event procedure to use the selected item or the entry as edited in the text box portion of the control.

The selected item, and other fields of the Recordset used to build the list, can be referenced by using the bookmark provided in the SelectedItem property.

Whenever you successfully change BoundColumn or ListField in the DBList or DBCombo control, the Refill method is invoked and the list is rebuilt from the chosen Recordset field.

Searching the List

If you enable the extended search mode using the MatchEntry property, you can easily locate items in the list generated by the DBCombo or DBList controls.  After focus is given to the list, any keys the user types are concatenated to a search argument.  For example, if the user types N, an N is concatenated to the search argument and the control positions to the first matching item in the list.  If the user subsequently types E, the process is repeated and the control positions to the first item beginning with the letters NE.  The search argument is cleared when the control gains the focus, or when the user presses backspace or hesitates for a few seconds.

If you select standard search mode, the search argument is limited to one character.

Only one item in the list can be selected at any time.  Once an item is selected, the SelectedItem property returns the bookmark for that row and the BoundText property contains the text of the selected item.  You can also select an item in the list using code by setting the BoundText property to one of the items in the list.  However, if the list is empty or you set the BoundText property to a value that isn't in the list, a trappable error occurs.  This can happen if the ListField or BoundColumn properties don't point to a valid source of data.

Controlling the Display

If the number of items exceeds the number that can be displayed, a scroll bar is automatically added to the control.  Use the IntegralHeight property to specify whether partial rows are displayed.  You can find out the number of visible items in the list by examining the VisibleCount property.

If you don't specify a ListField property, the BoundColumn property is used to fill the list.  If you don't supply a BoundColumn property, a trappable error results.


See Also

BoundColumn Property

BoundText Property

ComboBox Control

DataField Property

DataSource Property

DBCombo Control

DBGrid Control

DBList Control

IntegralHeight Property

ListBox Control

ListField Property

MatchEntry Property

Recordset Object, Recordsets Collection

RowSource Property

SelectedItem Property

Text Property

UpdateRecord Method

VisibleCount Property

VisibleItems Property


Connecting to ODBC Databases

See Also

Visual Basic applications can connect to any database with an ODBC driver.  Connecting to ODBC database tables can be accomplished in a variety of ways:

Attach an ODBC database table or view to a Microsoft Jet database and use the OpenRecordset method to access the table.

Open the ODBC database directly using the OpenDatabase method.

Create a Querydef object that references an ODBC database.

Use the Data control to open either an attached ODBC table or the ODBC database directly.

Use the ODBC API as supplied in the ODBC programmer's toolkit.

Before any application can access an ODBC database, the ODBC drivers must be installed and a Data Source Name (DSN) created using the Control Panel or the RegisterDatabase method.  Whenever you refer to an ODBC database, this DSN is used.  It contains the linkage information used by the ODBC drivers and the Microsoft Jet database engine to establish a connection to the database.  Visual Basic includes an ODBC setup disk that can be freely copied when you distribute your application.  When you are ready to open an ODBC database, use the DSN in the Connect property of the Data control or QueryDef object or in the source argument of the OpenDatabase method.

For example, to directly open an ODBC database using the Data control, you could either enter the string shown below in the Connect property using the Property window, or use the following code:

Data1.Connect = "ODBC;DSN=MySQLServer;" _

& "UID=Fred;PWD=APlus;DATABASE=MySSDB;"

Data1.Database = ""

Data1.Refresh

In the same way you can provide a source argument to the OpenDatabase method:

Dim Db as Database, Connect as String

Connect$ = "ODBC;DSN=MySQLServer;" _

& "UID=Fred;PWD=APlus;DATABASE=MySSDB;"

Set Db = OpenDatabase("", False, False, Connect$)

Performance Considerations

For best efficiency, you should not connect directly to an ODBC database.  When you do, the Jet engine is forced to query the database to determine table schema.  As each Recordset is created, this process may be repeated to determine the structure of the tables and indexes accessed.  This extra overhead can significantly increase the time it takes to open an ODBC database and retrieve data from its tables.

A higher-performance alternative when accessing ODBC databases is to attach chosen ODBC database tables or views to a Jet database.  By using this technique, the Jet engine is able to determine the structure of the table when it is attached.  When the database is subsequently opened or accessed, the linkage information stored in the Jet database is referenced.  If the ODBC database structure changes, however, use the TableDef object's RefreshLink method to rebuild the linkage information.  Attached tables may be updatable, but you can't use SQL PassThrough queries with these tables.

To perform many of its operations more quickly on Microsoft SQL Server systems, the ODBC driver may create one or more stored procedures in your working database.  If your program terminates abnormally, these procedures may remain on the server.  Generally, it is safe to remove these procedures manually once you determine they are not being used.

To adjust the parameters used by the Jet engine when working with ODBC databases, create a special table, MSysConf, on each ODBC database that you expect to access from Visual Basic using the Jet engine.

Executing SQL Statements Directly

In cases where you need to execute SQL statements that can only be executed on the ODBC database, like Transact SQL statements on Microsoft SQL Server, or to execute stored procedures, open the database directly or create a Querydef object whose Connect property contains an ODBC connect string.  The ExecuteSQL method only works with directly opened ODBC databases.  The Jet engine can return multiple result sets and messages from stored procedures when you use a Querydef to execute the procedure.

When using ODBC databases, the LockEdits property is always False.  The Jet engine defaults to optimistic locking.  You can only update ODBC database tables if a unique key exists for the table.  If you need to use and update an external temporary table, create an index for it before attaching to or opening it directly.

You can set an upper limit on the time that the Jet engine takes to open an ODBC database by setting the LOGINTIMEOUT argument in the Connect string.  You can also limit the time the Jet engine takes to execute an ODBC query by setting the QueryTimeout property of the Database object or the ODBCTimeout property of the Querydef object.  When any of these preset times expire, a trappable error occurs.


See Also

Accessing External Databases

Connect Property

CreateQueryDef Method

Data Control

Database Object, Databases Collection

ExecuteSQL Method

LockEdits Property

ODBCTimeout Property

OpenDatabase Method

OpenRecordset Method

Querydef Object, QueryDefs Collection

QueryTimeout Property

RefreshLink Method

TableDef object, TableDefs Collection

Using SQL PassThrough

Using the MSysConf Table with SQL Databases


Refill Method

See Also	Applies To

Forces repaint of a bound control and calls restart to re-create the list.  Doesn't support named arguments.

Syntax

object.Refill

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The Refill method is different than the standard Refresh method, which just forces a Repaint event.


See Also

Data Control

Refresh Method (Data Access)


Refill Method Applies To

DBCombo Control

DBList Control


UpdateControls Method

See Also	Applies To

Gets the current record from a Data control's Recordset object and displays the appropriate data in controls bound to a Data control.  Doesn't support named arguments.

Syntax

object.UpdateControls

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use this method to restore the contents of bound controls to their original values, 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.


See Also

Edit Method

Update Method

UpdateRecord Method


UpdateControls Method Applies To

Data Control


UpdateRecord Method

See Also	Applies To

Saves the current values of bound controls.  Doesn't support named arguments.

Syntax

object.UpdateRecord

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

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.  Using this method avoids creating a cascading event.

The UpdateRecord method has the same effect as executing the Edit method, changing a field, and then executing the Update method, except that no events occur.

You can use this method to avoid triggering the Validate event.

Whenever you attempt to update a record in the database, any validation rules must be satisfied before the record is written to the database.  These rules are established by setting the ValidationRule property or, in the case of Microsoft SQL Server, by Transact SQL defaults, rules, and triggers written to enforce referential and data integrity.

In some cases, the update may not occur because the operation violates referential integrity constraints, the page containing the record is locked, the database or Recordset object isn't updatable, or the user doesn't have permission to perform the operation.  Any of these conditions generates a trappable error.


See Also

Update Method

UpdateControls Method


UpdateRecord Method Applies To

Data Control


CellText Method

See Also	Example	Applies To

Returns a formatted text value from a DBGrid control cell.  Doesn't support named arguments.

Syntax

object.CellText bookmark

The CellText method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

bookmark	Required.  A string expression that represents a row in the DBGrid control.

Remarks

The CellText method returns a formatted string representation of the data in the current column for the row specified by the bookmark value.  Using the CellText method is similar to accessing the Text property, except that you can select a specific row from which to retrieve the value.

The value returned by the CellText method is derived from the Text property by applying the formatting as specified by the NumberFormat property of the Column object.

When using the CellText method, a specific DBGrid control cell is selected by setting the Col property to the desired column number and setting the CellText method's bookmark argument to a specific record.

Using the CellText method to extract information from a cell doesn't affect the current selection.


See Also

Add Method (DBGrid)

Bookmark Property

CellValue Method

Col, Row Properties

ColIndex Property

Column Object, Columns Collection

Data Control

DBGrid Control

NumberFormat Property

Text Property

Value Property


CellText Method Applies To

Column Object


CellText Method Example

This examples gets information from the top and bottom rows and displays it in a label.

Sub DataGrid1_Scroll (Cancel As Integer)

Dim TopRow, BottomRow

TopRow = DataGrid1.Columns(1).CellText(DataGrid1.FirstRow)

BottomRow = DataGrid1.Column(1).CellText(DataGrid1.RowBookmark_

 (DataGrid1.VisibleRows - 1))

Label1.Caption = "Records " & TopRow & " to " & _

 BottomRow & " are currently displayed."

End Sub


CellValue Method

See Also	Example	Applies To

Returns a raw data value in a column for a specified row specified in a DBGrid control.  Doesn't support named arguments.

Syntax

object.CellValue bookmark

The CellValue method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

bookmark	Required.  A string expression that contains the unformatted data stored in a selected DBGrid control cell.

Remarks

You select a specific DBGrid control cell is by setting the Col property to the desired column number and the CellValue method's bookmark argument to a specific record.

Using the CellValue method returns the same value as the Value property setting of the current Column object, except that you can specify a specific row in the DBGrid control to reference.

Using the CellValue method to extract information from a cell doesn't affect the current selection.


See Also

Bookmark Property

Col, Row Properties

ColIndex Property

Data Control

DBGrid Control

NumberFormat Property

Text Property

Value Property


CellValue Method Applies To

Column Object


CellValue Method Example

This example retrieves all the values in a given column from the selected range of rows and loads them into an array.

Sub Command1_Click ()

Dim I

ReDim CalcArray (0 to DataGrid1.SelBookmarks.Count - 1)

For I = 0 to DataGrid1.SelBookmarks.Count -1

' Puts the value of the current row in the selected row

' array into corresponding CalcArray cell.

CalcArray(I) = _

 DataGrid1.Columns(1).CellValue(DataGrid1.SelBookmarks(I))

Next I

End Sub


ColContaining Method

See Also	Example	Applies To

Returns the ColIndex value of the DBGrid control column containing the specified coordinate (X) value.  Doesn't support named arguments.

Syntax

object.ColContaining coordinate

The ColContaining method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

coordinate	Required.  A single numeric expression that defines a horizontal coordinate (X value) based on the coordinate system of the container.

Remarks

The ColContaining method returns a number that corresponds to one of the column indexes of the control specified by object.  This number ranges from 0 to 1 less than the setting of the Count property of the Columns collection (0 to Columns.Count -1).  This method is useful when working with mouse and drag events when you are trying to determine where the user clicked or dropped another control in terms of a column of the DBGrid control.

If coordinate is outside of the coordinate system of the container, a trappable error occurs.

Note   The ColContaining method returns the ColIndex of the column indicated, not the visible column.  If coordinate falls in the first visible column, but two columns have been scrolled off the left side of the control, the ColContaining method returns 2.


See Also

ColIndex Property

Column Object, Columns Collection

Data Control

RowContaining Method


ColContaining Method Applies To

DBGrid Control


GetBookmark Method

See Also	Example	Applies To

Returns a value containing a bookmark for a row relative to the current row in a DBGrid control.  Doesn't support named arguments.

Syntax

object.GetBookmark value

The GetBookmark method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	Required.  A long  numeric expression that addresses rows of the DBGrid control relative to the current row, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	Returns bookmark of the current row [image] the same as DBGrid1.Bookmark.

1	Returns bookmark of the row following current row.

-1	Returns bookmark of the row preceding current row.

n	Returns bookmark of the row relative to current row based on (DBGrid1.Row + n)

Remarks

The GetBookmark method may return values that are very different from the RowBookmark method because the current row may not be visible.


See Also

Bookmark Property

Data Control

DBGrid Control

RowBookmark Method


GetBookmark Method Applies To

DBGrid Control


GetBookmark Method Example

This example checks the updated value of a particular column to make sure that the new value lies between the values of the previous and the next rows.

Sub DataGrid1_BeforeColUpdate (ColIndex As Integer, _

 OldValue as Variant, PrevVal, NextVal, CurVal, Cancel As Integer)

If ColIndex = 1 Then

PrevVal = DataGrid1.Columns(1).CellValue(_

 DataGrid1.GetBookmark(-1))

NextVal = DataGrid1.Columns(1).CellValue(_

 DataGrid1.GetBookmark(1))

CurVal = DataGrid1.Columns(1).Value

If CurVal > PrevVal Or CurVal < NextVal  Then

Cancel = True

MsgBox "Value must be between" & PrevVal _

 & " and " & NextVal

End If

End If

End Sub


Add Method (DBGrid)

See Also	Applies To

Adds a new column to the Columns collection or a new bookmark to the SelBookmarks collection of the DBGrid control.  Doesn't support named arguments.

Syntax

object.Add(colindex)

object.Add bookmark

The Add method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

colindex	Required.  An integer that specifies where the new Column object is inserted in the Columns collection, as described in Settings.

bookmark	The bookmark to be added to the collection.

Settings

The settings for colindex are:

Setting	Description

0	Inserts new column as leftmost column.

Count	If the colindex argument is the same as the Count property setting, the new column is inserted as the rightmost column.

n	Inserts the new column to the left of the nth column in the Columns collection. The nth column and all subsequent columns are incremented accordingly.

Remarks

The Add method inserts a new Column object into the Columns collection based on the colindex argument.  New columns are added with their Visible property set to False and all other properties set to their default values.  Initially, new columns are unbound because the DataField property is set to a zero-length string ("").  The Count property of the Columns collection is incremented to reflect the new column.

Use the Add method to add bookmarks to the SelBookmarks collection.  Once a bookmark is appended to the SelBookmarks collection, it appears selected in the DBGrid control.


See Also

ColIndex Property

Data Control

DBGrid Control

Remove Method (Data Access)


Add Method (DBGrid) Applies To

Columns Collection

SelBookmarks Collection


Rebind Method

See Also	Example	Applies To

Re-creates the DBGrid control properties and columns.  Doesn't support named arguments.

Syntax

object.Rebind

Remarks

The Rebind method causes the DBGrid control to perform the same operations that occur when you set the DataSource property.  The DBGrid control resets the columns, headings and other properties based on the current Data control properties.


See Also

Data Control

DBGrid Control

Refresh Method (Data Access)

Requery Method


Rebind Method Applies To

DBGrid Control


Rebind Method Example

This example checks a global variable to see if the user changed the table layout and reconfigures using the original table information.

Sub CheckForRebind_Click ()

If UserChangedLayout Then

DataGrid1.Rebind

End If

End Sub


Remove Method (Data Access)

See Also	Applies To

Removes the specified item from the SelBookmarks collection of selected rows in a DBGrid object or a Column object from the Columns collection of a DBGrid control.  Doesn't support named arguments

Syntax

object.Remove index | bookmark

The Remove method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

index	Required.  An integer in the range of 0 to the Count property setting of the collection - 1.

bookmark	Required.  A string expression that contains the unformatted data stored in a selected cell of a DBGrid control.

Remarks

The Remove method deselects a row from the DBGrid, removes the bookmark from the SelBookmarks collection, and decrements the Count property setting of the DBGrid control.  Rows to be removed can be selected using the row index, or one of the row bookmarks.  If you specify a row that isn't in the SelBookmarks collection, a trappable error occurs.


See Also

Add Method (DBGrid)

ColIndex Property

Data Control

DBGrid Control


 Remove Method Applies To

Columns Collection

SelBookmarks Collection


RowBookmark Method

See Also	Example	Applies To

Returns a value containing a bookmark for a visible row in the DBGrid control.  Doesn't support named arguments.

Syntax

object.RowBookmark value

The RowBookmark method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	Required.  An integer in the range of 0 to the setting of the DBGrid control's VisibleRows property minus 1.

Remarks

RowBookmark(0) returns the same bookmark as the FirstRow property of the DBGrid control.  The current row, as determined by the DBGrid control's Bookmark property, may not be returned by this method if the current row isn't visible.

Note   The bookmarks returned by RowBookmark should not be saved because their values change as soon as rows visible in the DBGrid control change.


See Also

Bookmark Property

FirstRow Property

GetBookmark Method

SelBookmarks Collection

SelBookmarks Property

VisibleRows Property


RowBookmark Method Applies To

DBGrid Control


RowBookmark Method Example

This example selects all the rows that are currently visible on the grid.

Sub SelectAllVisible_Click ()

Dim I

For I = 0 To DataGrid1.VisibleRows - 1

DataGrid1.SelBookmarks.Add DataGrid1.RowBookmark(I)

Next I

End Sub


RowContaining Method

See Also	Example	Applies To

Returns a value corresponding to the row number of the specified vertical (Y) coordinate of the DBGrid control.  Doesn't support named arguments.

Syntax

object.RowContaining coordinate

The RowContaining method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

coordinate	Required.  A single numeric expression that specifies a vertical coordinate (Y value) based on the coordinate system of the container.

Remarks

The RowContaining method returns a value that corresponds to one of the column indexes of the control specified by object.  This value ranges from 0 to the setting of the VisibleRows property -1.  This method is useful when working with mouse and drag events when you are trying to determine where the user clicked or dropped another control in terms of a row of the DBGrid control.

If coordinate is outside of the coordinate system of the container, a trappable error occurs.


See Also

ColContaining Method

ColIndex Property

Column Object, Columns Collection

Data Control


RowContaining Method Applies To

DBGrid Control


RowContaining, ColContaining Method Example

This example saves the value of the cell where the user began a drag method.

Dim SaveValue

Sub DataGrid1_MouseDown (Button As Integer, Shift As Integer, _

 X As Single, Y As Single)

Dim RowValue, ColValue

' Get the value of the row and column that the mouse is over

RowValue = DataGrid1.RowContaining Y

ColValue = DataGrid1.ColContaining X

' If the values are both valid, save the text of the cell and

' begin dragging.

If RowValue > 0 And RowValue < DataGrid1.VisibleRows And _

 ColValue > 0 And ColValue < DataGrid1.VisibleCols Then

SaveValue = DataGrid1.Columns(ColValue)._

CellValue(DataGrid1.RowBookmark(RowValue))

DataGrid1.Drag 1

End If

End Sub


RowTop Method

See Also	Example	Applies To

Returns a value containing the Y coordinate of the top of a specified row of a DBGrid control.  Doesn't support named arguments.

Syntax

object.RowTop value

The RowTop method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	Required.  An integer that specifies a row in the range of 0 to the setting of the VisibleRows property -1.

Remarks

The RowTop method returns a value that corresponds to the Y coordinate of the top of the row specified by value.  The return value is based on the ScaleMode property of the container.

You can use the RowTop method with the RowHeight, Left, and Width properties of the Column object to determine the exact location and dimension of a chosen cell in the DBGrid control.


See Also

ColContaining Method

Column Object, Columns Collection

Data Control

Left, Top Properties

RowHeight Property

VisibleRows Property

Height, Width Properties


 RowTop Method Applies To

DBGrid Control


RowTop Method Example

This example begins a drag operation in the grid.  Using the grid cell location and size properties, a Label control the size of the cell is used as the drag object.

Sub DataGrid1_MouseDown (Button As Integer, Shift As Integer, _

 X As Single, Y As Single)

' Declare variables.

Dim DY, DX, RowValue, ColValue, CellLeft, CellTop

ColValue = DataGrid1.ColContaining(X)

RowValue = DataGrid1.RowContaining(Y)

DY = DataGrid1.RowHeight	' Get the height of the cell.

DX = DataGrid1.Columns(ColValue).Width  ' Get the width of the cell.

CellLeft = DataGrid1.Columns(ColValue).Left

CellTop = DataGrid1.RowTop RowValue + Y - DY /2

Label1.Move CellLeft, CellTop, DX, DY

Label1.Drag	' Drag label outline.

End Sub


Scroll Method

See Also	Example	Applies To

Scrolls the DBGrid control horizontally and vertically in a single operation.  Doesn't support named arguments.

Syntax

object.Scroll colvalue, rowvalue

The Scroll method syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

colvalue	Required.  A long numeric expression that specifies a column in the control.

rowvalue	Required.  A long numeric expression that specifies a row in the control.

Remarks

Positive values scroll right and down.  Negative values scroll left and up.  Values that are out of range don't cause an error [image] the DBGrid control scrolls to the maximum degree possible.  The same effect can be achieved by setting the TopRow and Left properties, but these must be set independently, causing two separate Paint events.


See Also

Left, Top Properties

TopRow Property


Scroll Method Applies To

DBGrid Control


Scroll Method Example

This example creates two buttons that enable you to scroll diagonally, one to move down and to the right and the other to move up and to the left.

Sub ScrollDownRight_Click

' Scroll down and to the right.

DataGrid1.Scroll DataGrid1.VisibleCols, DataGrid1.VisibleRows

End Sub

Sub ScrollUpLeft_Click

' Scroll up and to the left.

DataGrid1.Scroll -DataGrid1.VisibleCols, -DataGrid1.VisibleRows

End Sub


Database Property

See Also	Example	Applies To

Returns a reference to a Data control's underlying Database object.

Syntax

object.Database

Set databaseobject = object.Database (Professional Edition only)

The Database property syntax has these parts:

Part	Description

databaseobject	An object expression that evaluates to an valid Database object created by the Data control.

object	An object expression that evaluates to an object in the Applies To list.

Remarks

The Database object created by the Data control is based on the control's DatabaseName, Exclusive, ReadOnly, and Connect properties.

Database objects have properties and methods you can use to manage your data.  You can use any method 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.

Although you can create a Recordset object and pass it to a Data control's Recordset property, you can't open a database and pass the newly created Database object to the Data control's Database property.


Database Property Applies To

Data Control


See Also

Connect Property

Data Access Overview

Data Control

Database Object, Databases Collection

DatabaseName Property

Exclusive Property

Field Object, Fields Collection

Index Object, Indexes Collection

Name Property

ReadOnly Property

Recordset Property

TableDef Object, TableDefs Collection


DatabaseName Property

See Also	Example	Applies To

Returns or sets the name and location of the source of data for a Data control.

Syntax

object.DatabaseName [ = pathname ]

The DatabaseName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pathname	A string expression that indicates the database file(s) location.

Remarks

If your network system supports it, the pathname argument can be a fully qualified network path name such as \\MYSERVER\MYSHARE\DATABASE.MDB.

The database type is indicated by the file or directory that pathname points to, as follows:

pathname Points To...	Database Type

.MDB file	Microsoft Access database

.DDF file	Btrieve database

Directory containing .DBF file(s)	dBASE database

Directory containing .XLS file	Microsoft Excel database

Directory containing .DBF files(s)	FoxPro database

Directory containing .PDX file(s)	Paradox database

Directory containing appropriate database files	Text format database

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 object is open, you must use the Refresh method to open the new database.

Note   For better performance when accessing external databases, it's recommended that you attach external database tables to a Microsoft Jet engine database (.MDB) and use the name of this database in the DatabaseName property.


DatabaseName Property Applies To

Data Control


See Also

Accessing External Databases

Connect Property

Data Control

OpenDatabase Method

Refresh Method

RegisterDatabase Method


DataChanged Property

See Also	Applies To

Returns or sets a value indicating that the data in the bound control has been changed by some process other than that of retrieving data from the current record.  Not available at design time.

Syntax

object.DataChanged [= value]

The DataChanged property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that indicates whether data has changed, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	The data currently in the control isn't 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, it passes data from fields in the current record to controls bound to the specific field or the entire record.  As data is displayed in the bound controls, the DataChanged property is set to False.  If the user or any other operation changes the value in the bound control, the DataChanged property is set to True.  Simply moving to another record doesn't affect the DataChanged property.

When the Data control starts to move to a different record, the Validate event occurs.  If DataChanged is True for any bound control, the Data control automatically invokes the Edit and Update methods to post the changes to the database.

If you don't wish to save changes from a bound control to the database, you can set the DataChanged property to False in the Validate event.

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.


DataChanged Property Applies To

CheckBox Control

DBCombo Control

DBList Control

Image Control

Label Control

PictureBox Control

TextBox Control


See Also

Change Event

Data Access Overview

Data Control

Edit Method

Update Method

UpdateRecord Method

Validate Event


DataField Property

See Also	Applies To

Returns or sets a value that binds a control to a field in the current record

Syntax

object.DataField [= value]

The DataField property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that evaluates to the name of one of the fields in the Recordset object specified by a Data control's RecordSource and DatabaseName properties.

Remarks

Bound controls provide access to specific data in your database.  Bound controls that manage a single field typically display the value of a specific 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 Recordset object created by the Data control.  Together, these properties specify what data appears in the bound control.

When you use a QueryDef object or SQL statement that returns the results of an expression, the field name is automatically generated by the Microsoft Jet database engine.  For example, when you code an SQL aggregate function or an expression in your SQL query, unless you alias the aggregate fields using an AS clause, the field names are automatically generated.  Generally, the expression field name is Expr1 followed by a three-character number starting with 000.  The first expression returned would be named Expr1000.

It's recommended that you code your SQL queries to alias expression columns as shown below:

Data1.RecordSource = "Select AVG(Sales)  " _

& " AS AverageSales From SalesTable"

MyText.DataField = "AverageSales"

MyText.DataSource = Data1

Data1.Refresh

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


DataField Property Applies To

CheckBox Control

ComboBox Control

DBCombo Control

DBGrid Control

DBList Control

Image Control

Label Control

ListBox Control

PictureBox Control

TextBox Control


See Also

Binding a Control to a Data Control

CheckBox Control

ComboBox Control

Data Control

DataSource Property

DBCombo Control

DBGrid Control

DBList Control

Image Control

Label Control

ListBox Control

PictureBox Control

Recordset Property

SELECT Statement (SQL)

TextBox Control


DataSource Property

See Also	Applies To

Sets a value that specifies the Data control through which the current control is bound to a database.  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 the DataSource property at design time using the Properties window.

To complete the connection with a field in the Recordset managed by the Data control, you must also provide the name of a Field object in the DataField property.  Unlike the DataField  property, the DataSource property setting isn't available at run time.


DataSource Property Applies To

CheckBox Control

ComboBox Control

DBCombo Control

DBGrid Control

DBList Control

OLE Container Control

Image Control

Label Control

ListBox Control

PictureBox Control

TextBox Control


See Also

Binding a Control to the Data Control

ComboBox Control

Data Access Overview

Data Control

DataField Property

ListBox Control

Recordset Property

RecordSource Property


Exclusive Property

See Also	Applies To

Returns or sets a value that indicates whether the underlying database for a Data control is opened for single-user or multiuser access.

Syntax

object.Exclusive [ = value]

The Exclusive property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines user access, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	The database is open for single-user access.  No one else can open the database until it's closed.

False	(Default) The database is open for multiuser access.  Other users can open the database and have access to the data while it's 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 method.

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 the database open, you can't open it for exclusive use and a trappable error results.

Database operations are faster if the database is opened for exclusive use.

After you open a database for exclusive use, your application can have as many instances open as necessary.  However, other applications running on your system are not permitted to open the database.

The Exclusive property is ignored for databases accessed through ODBC.


Exclusive Property Applies To

Data Control


See Also

Attributes Property

Close Method

Connect Property

Data Access Overview

DatabaseName Property

OpenDatabase Method

ReadOnly Property

Refresh Method


Options Property

See Also	Applies To

Returns or sets a value that specifies one or more characteristics of the Recordset object in the control's Recordset property.

Syntax

object.Options [ = value ]

The Options property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value that specifies a characteristic of a Recordset, as described in Settings.

Settings

Use one or more of the following values to set the Options property.  If you use more than one option, you must add their values:

Constant	Value	Description

dbDenyWrite	1	In a multiuser environment, other users can't make changes to records in the Recordset.

dbDenyRead	2	In a multiuser environment, other users can't read records (table-type Recordset only).

dbReadOnly	4	You can't make changes to records in the Recordset.

dbAppendOnly	8	You can add new records to the Recordset, but you can't read existing records.

dbInconsistent	16	Updates can apply to all fields of the Recordset, even if they violate the join condition.

dbConsistent	32	(Default) Updates apply only to those fields that don't violate the join condition.

dbSQLPassThrough	64	When using Data controls with an SQL statement in the RecordSource property, sends the SQL statement to an ODBC database, such as a SQL Server or Oracle database, for processing.

dbForwardOnly	256	The Recordset is a forward-only scrolling. The only move method allowed is MoveNext. This option cannot be used on Recordset objects manipulated with the Data control.

dbSeeChanges	512	Generate a trappable error if another user is changing data you are editing.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

If you change the Options 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 OpenRecordset method or the outdated CreateDynaset method.

To set more than one value for this property, you can combine options by adding values together.  For example, to set both dbReadOnly and dbInconsistent you can use this code:

Data1.Options = dbAppendOnly + dbInconsistent

To determine if the property contains a specific value, you can use the And operator.  For example, to find out if the Recordset is open for read-only access, you could use this code:

If Data1.Options And dbReadOnly Then...

Using both dbInconsistent and dbConsistent results in consistent updates, the default for Recordset objects.

Note   The dbSQLPassThrough option can only be used when creating dynaset- or snapshot-type Recordset objects and is supported only to provide compatibility with previous versions.  For better performance and functionality, you should use a previously created SQL PassThrough QueryDef object and set the Data control's Recordset property to a Recordset object created with the QueryDef.


Options Property Applies To

Data Control


See Also

CreateQueryDef Method

Data Access Overview

OpenRecordset Method

Recordset Property


ReadOnly Property (Data Access)

See Also	Applies To

Data control [image] returns or sets a value that determines whether the control's Database is opened for read-only access.

FileListBox control [image] returns or sets a value that determines whether a file list box contains files with read-only attributes.

Syntax

object.ReadOnly [= value]

The ReadOnly property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines read/write access, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	Data control [image] The control's Database object is opened with read-only access.  Changes to data aren't allowed.
FileListBox [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.
FileListBox control [image] No read-only files are listed in the control.

Remarks

Use the ReadOnly 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.  Accessing 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 method.

Use the ReadOnly property with a FileListBox control 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.


 ReadOnly Property (Data Access) Applies To

Data Control

FileListBox Control


See Also

Data Access Overview

Database Property

OpenDatabase Method

Path Property

Pattern Property

Refresh Method


RecordSource Property

See Also	Applies To

Returns or sets the underlying table, SQL statement, or QueryDef object for a Data control.

Syntax

object.RecordSource [= value ]

The RecordSource property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression specifying a name, as described in Settings.

Settings

The settings for value are:

Setting	Description

A table name	The name of one of the tables defined in the Database object's TableDefs collection.

An SQL query	A valid SQL string using syntax appropriate for the database.

A QueryDef	The name of one of the QueryDef objects in the Database object's QueryDefs collection.

Remarks

The RecordSource property specifies the source of the records accessible through bound controls on your form.

If you set the RecordSource property to the name of an existing table in the database, all of the fields in that table are visible to the bound controls attached to this Data control.  The order of the records retrieved is set by the Index object you select using the Index property of the Recordset.  If you don't set the Index property, the data is returned in no particular order.

If you set the RecordSource property to the name of an existing QueryDef in the database, all fields returned by the QueryDef are visible to the bound controls attached to the Data control.  The order of the records retrieved is set by the QueryDef object's query.  If the QueryDef doesn't specify an order, the data is returned in no particular order.

If you set the RecordSource property to an SQL statement that returns records, all fields returned by the SQL queryare visible to the bound controls attached to the Data control. This statement may include an ORDER BY clause to change the order of the records returned by the Recordset created by the Data control or a WHERE clause to filter the records.  If the database you specify in the Database and Connect property isn't a Microsoft Jet engine database, or if the dbSQLPassThrough option is set in the Options property, your SQL query must use the syntax required by that database engine.

Note   Whenever your QueryDef or SQL statement returns a value from an expression, the field name of the expression is created automatically by the Microsoft Jet database engine.  Generally, the name is Expr1 followed by a three-character number beginning with 000.  For example, the first expression would be named: Expr1000.

In most cases you'll want to alias expressions so you know the name of the column to bind to the bound control.  See the SQL SELECT statement AS clause for more information.

After changing the value of the RecordSource 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 and then use Refresh, the Recordset identifies the new object.  This may invalidate the DataField settings of bound controls and cause a trappable error.


RecordSource Property Applies To

Data Control


See Also

DatabaseName Property

DataField Property

DataSource Property

Querying a Database

QueryDef Object, QueryDefs Collection

Recordset Object, Recordsets Collection

Retrieving Data Using SQL

SELECT Statement (SQL)

Table Object


Recordset Property

See Also	Applies To

Returns or sets a Recordset object defined by a Data control's properties or by an existing Recordset object.

Syntax

object.Recordset [= value ]

The Recordset property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies a Recordset object.

Remarks

The Data control is automatically initialized when your application starts.  If the Connect, DatabaseName, Options, RecordSource, Exclusive, ReadOnly and RecordsetType properties are valid, or if you set these Data control properties at run time and use the Refresh method, the Microsoft Jet database engine attempts to create a new Recordset object based on those properties.  This Recordset is accessible through the Data control's Recordset property.

You can use the Recordset property as you would any other Recordset object.  For example, you can use any of the Recordset methods or properties and examine the structure of the Recordset object's underlying schema.

You can also request the type of Recordset to be created by setting the Data control's RecordsetType property.  If you don't request a specific type, a dynaset-type Recordset is created.  Using the RecordsetType property, you can request to create either a table-, snapshot- or dynaset-type Recordset.  However, if the Jet engine can't create the type requested, a trappable error occurs.

The type of Recordset created can be determined at run time by examining the Recordset property's Type property or the Data control's RecordsetType property.  Note, however, that the constants used for the type of Recordset created are different.  For example:

If Data1.Recordset.Type = dbOpenDynaset Then ...

If Data1.RecordsetType = dbDynasetType Then ...

A Recordset may not be updatable even if you request a dynaset- or table-type Recordset.  If the underlying database, table, or field isn't updatable, all or portions of your Recordset may be read-only.  Examine the Database and Recordset objects' Updatable property or the Field object's DataUpdatable property to determine if your code can change the records.

The number of records returned by the Recordset can be determined by moving to the last record in the Recordset and examining the Recordset object's RecordCount property.  The following example shows how you can combine the RecordCount property of a Recordset with the Recordset property to display the number of records in a Data control's recordset:

Data1.Recordset.MoveLast

MsgBox "Records: " & Data1.Recordset.RecordCount

Professional Edition

If you create a Recordset object using either code or another Data control, you can set the Recordset property of the Data control to this new Recordset.  Any existing Recordset in the Data control, and the Database object associated with it are released when a new Recordset is assigned to the Recordset property.

Note   When the Recordset property is set, the Data control doesn't close the current Recordset or Database, but it does release it.  If there are no other users, the database is closed automatically.  You may wish to consider closing the Recordset and Database associated with the Data control prior to setting the Recordset property.

Make sure the DataField properties of the bound controls connected to the Data control are set to match the new Recordset object's field names.

For example, to create a Recordset in code and pass it to an existing Data control:

Dim Db As Database, Rs As Recordset	' Defined as public variables.

Sub ApplyRecordset()

Set Db = Workspaces(0).OpenDatabase("MYDB.MDB")

Set Rs = Db.OpenRecordset("MyTable") ' Defaults to Table object.

Set Data1.Recordset = Rs	' Assign Recordset.

Data1.Recordset.Index = "MyIndex"

Debug.print Rs.Type	' Show type created.

End Sub

You can use this technique to create an MDI parent and child data connection with a single hidden Data control on the MDI parent form and another visible Data control on the MDI child.  In the MDI child's Form_Load event, set the child's Data control Recordset property to the parent's Data control Recordset property.  Using this technique synchronizes all the child forms and their bound controls with the parent.

All Recordsets created by the Data control are built in Workspaces(0).  If you need to use the Data control to manipulate a database in another Workspace, use the technique shown above to open the database in the desired Workspace, create a new Recordset and set the Data control's Recordset property to this new Recordset.

Important   You can always reference the properties of the Data control's Recordset by using the Recordset property.  By directly referencing the Recordset, you can determine the Index to use with Table objects, the Parameters collection of a QueryDef, or the Recordset type.


Recordset Property Applies To

Data Control


See Also

DataField Property

DataUpdatable Property

FindFirst, FindLast, FindNext, FindPrevious Methods

Index Property

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Options Property

RecordCount Property

Recordset Object, Recordsets Collection

RecordsetType Property

RecordSource Property

Type Property

Updatable Property


BOFAction, EOFAction Properties

See Also	Applies To

Returns or sets a value indicating what action the Data control takes when the BOF or EOF properties are True.

Syntax

object.BOFAction [= value]

object.EOFAction [= value]

The BOFAction and EOFAction property syntaxes have these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value that specifies an action, as described in Settings.

Settings

For the BOFAction property, the settings for value are:

Setting	Value	Description

vbBOFActionMoveFirst	0	MoveFirst (Default): Keeps the first record as the current record.

vbBOFActionBOF	1	BOF: Moving past the beginning of a Recordset triggers the Data control Validate event on the first record, followed by a Reposition event on the invalid (BOF) record.  At this point, the Move Previous button on the Data control is disabled.

For the EOFAction property, the settings for value are:

Setting	Value	Description

vbEOFActionMoveLast	0	MoveLast (Default): Keeps the last record as the  current record.

vbEOFActionEOF	1	EOF: Moving past the end of a Recordset triggers the Data control's Validation event on the last record, followed by a Reposition event on the invalid (EOF) record.  At this point, the MoveNext button on the Data control is disabled.

vbEOFActionAddNew	2	AddNew: Moving past the last record triggers the Data control's Validation event to occur on the current record, followed by an automatic AddNew, followed by a Reposition event on the new record.

Remarks

These constants are listed in the Visual Basic (VB) object library in the Object Browser.

If you set the EOFAction property to vbEOFActionAddNew, once the user moves the current record pointer to EOF using the Data control, the current record is positioned to a new record in the copy buffer.  At this point you can edit the newly added record.  If you make changes to the new record and the user subsequently moves the current record pointer using the Data control, the record is automatically appended to the Recordset.  If you don't make changes to this new record, and reposition the current record to another record, the new record is discarded.  If you use the Data control to position to another record while positioned over this new record, another new record is created.

When you use code to manipulate Recordsets created with the Data control, the EOFAction property has no effect [image] it only takes effect when manipulating the Data control with the mouse.

In situations where the Data control Recordset is returned with no records, or after the last record has been deleted, using the vbEOFActionAddNew option for the EOFAction property greatly simplifies your code because a new record is always editable as the current record.


See Also

BOF, EOF Properties

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

RecordCount Property

Recordset Object, Recordsets Collection

RecordSource Property

Type Property


BOFAction, EOFAction Properties Applies To

Data Control


IntegralHeight Property

See Also	Applies To

Returns or sets a value indicating if the control displays partial items.  Read-only at run time.

Syntax

object.IntegralHeight [= value ]

The IntegralHeight property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether the list is resized, as described in Settings.

Settings

The settings for value are:

Setting	Description

True 	(Default) The list resizes itself to display only complete items.

False 	The list doesn't resize itself even if the item is too tall to display completely.


See Also

Binding a Control to a Data Control

Bound Data Controls

Data Control


IntegralHeight Property Applies To

ComboBox Control

DBCombo Control

DBList Control

ListBox Control


MatchEntry Property

See Also	Applies To

Returns or sets a value indicating how the DBCombo or DBList control performs searches based on user input.

Syntax

object.MatchEntry [= value ]

The MatchEntry property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value that defines the behavior of a control when it has focus and the user enters one or more characters, as described in Settings.

Settings

The settings for value are:

Setting	Value	Description

vbMatchEntrySimple	0	Basic Matching: (Default) The control searches for the next match for the character entered using the first letter of entries in the list.  Repeatedly typing the same letter cycles through all of the entries in the list beginning with that letter.

vbMatchEntryExtended	1	Extended Matching:  The control searches for an entry matching all characters entered.  The search is done as characters are being typed, further refining the search.

Remarks

When the MatchEntry property is set to vbMatchEntryExtended and the user enters a backspace or waits more than a few seconds, the matching string is reset.


See Also

Binding a Control to a Data Control

Bound Data Controls

Data Control


MatchEntry Property Applies To

DBCombo Control

DBList Control


RecordsetType Property

See Also	Example	Applies To

Returns or sets a value indicating the type of Recordset object you want the Data control to create.

Syntax

object.RecordsetType [= value ]

The RecordsetType property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A constant or value that specifies a type of Recordset, as described in Settings.

Settings

The settings for value are:

Setting	Value	Description

vbRSTypeTable	0	A table-type Recordset.

vbRSTypeDynaset	1	(Default) A dynaset-type Recordset.

vbRSTypeSnapshot	2	A snapshot-type Recordset.

Remarks

If the Microsoft Jet database engine can't create the type of Recordset you requested, a trappable error occurs.

If you don't specify a RecordsetType before the Data control creates the Recordset, a dynaset-type Recordset is created (if possible).

If you create a Recordset without using the Data control (even with another Data control) and set the Recordset property with this new Recordset object, the RecordsetType property of the Data control is set to the Recordset.Type property of the new Recordset.

Important   The RecordsetType property value doesn't correspond to the value used to identify Recordset object types.  See the OpenRecordset method or the Type property for details.

Note   The Data control doesn't support the outdated Dynaset object.  By default it creates a dynaset-type Recordset that is completely compatible with the Dynaset so any existing code shouldn't have to be modified.


See Also

Dynaset-Type Recordset

OpenRecordset Method

Recordset Object, Recordsets Collection

Refresh Method

Requery Method

Snapshot-Type Recordset

Table-Type Recordset

Type Property


RecordsetType Property Applies To

Data Control


AllowAddNew Property

See Also	Example	Applies To

Returns or sets a value indicating whether the user can add new records to the Recordset object underlying a DBGrid control.

Syntax

object.AllowAddNew [= value]

The AllowAddNew property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether a user can add new records, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	Users can add records to the Recordset object underlying the DBGrid control.

False	Users can't add records to the Recordset underlying the DBGrid control.

Remarks

The last row displayed in the DBGrid control is left blank to permit users to enter new records.  If the AllowAddNew property is False, users can't give focus to this row.

The underlying Recordset may not enable insertions even if the AllowAddNew property is True.  In this case, an error occurs when the user tries to add a record.


See Also

AllowDelete Property

AllowUpdate Property

Data Control


AllowAddNew Property Applies To

DBGrid Control


AllowAddNew, AllowDelete, AllowUpdate Properties Example

This example checks the value of a check box.  If it is False, the user can't make changes to the grid.

Private Sub Form_Load ()

If Check1.Value = 0 Then

DataGrid1.AllowDelete = False

DataGrid1.AllowAddNew = False

DataGrid1.AllowUpdate = False

End If

End Sub


AllowDelete Property

See Also	Applies To

Returns or sets a value indicating whether the user can delete records from the Recordset object underlying a DBGrid control.

Syntax

object.AllowDelete [= value]

The AllowDelete property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether a user can delete records, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	Users can delete records from the Recordset object underlying the DBGrid control.

False	Users can't delete records from the Recordset underlying the DBGrid control.

Remarks

Use the AllowDelete property to prevent the user from deleting records from the Recordset through interaction with the DBGrid control.

The underlying Recordset may not enable deletions even if the AllowDelete property is True for the DBGrid control.  In this case, an error occurs when the user tries to delete a record.


See Also

AllowAddNew Property

AllowUpdate Property

Data Control


AllowDelete Property Applies To

DBGrid Control


AllowSizing Property

See Also	Example	Applies To

Returns or sets a value indicating whether a user can resize columns in the DBGrid control.

Syntax

object.AllowSizing [= value]

The AllowSizing property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether a column can be resized, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	User can resize column.

False	User can't resize column.

Remarks

If the AllowSizing property is True, the mouse pointer turns into a double-headed (Size W E) arrow when positioned over the row divider of the specified column, and the user can resize the column by dragging.  Any change in column size causes a ColResize event.

All rows of the DBGrid control are always the same height, which is determined by the RowHeight property.


See Also

AllowRowSizing Property

ColResize Event

Data Control

DefColWidth Property

RowHeight Property

RowResize Event

VisibleRows Property


AllowSizing Property Applies To

Column Object


AllowSizing Property Example

This example prevents the user from resizing or editing the first three columns of the grid.

Private Sub Form_Load ()

Dim I

For I = 0 to 2

DataGrid1.Columns(I).AllowSizing = False

DataGrid1.Columns(I).Locked = False

Next I

End Sub


AllowRowSizing Property

See Also	Example	Applies To

Returns or sets a value indicating whether a user can resize the rows of the DBGrid control.

Syntax

object.AllowRowSizing [= value]

The AllowRowSizing property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether a user can resize rows, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	Rows can be sized by the user.

False	Rows can't be sized by the user.

Remarks

If the AllowRowSizing property is True, the mouse pointer turns into a double-headed (Size N S) arrow when positioned over the row divider between any record selectors, and the user can resize the rows by dragging.  Any change in row size causes a RowResize event.

All rows of the DBGrid control are always the same height, which is determined by the RowHeight property.


See Also

Data Control

DefColWidth Property

RowHeight Property

RowResize Event

VisibleRows Property


AllowRowSizing Property Applies To

DBGrid Control


AllowRowSizing Property Example

This example checks the database to see if it has any memo fields; if not, row resizing is disabled.

Private Sub Form_Load

Dim Fld As Field

DataGrid1.AllowRowSizing = False

For Each Fld in Data1.Recordset.Fields

If Fld.Type = dbMemo Then

DataGrid1.AllowRowSizing = True

DataGrid1.RowHeight = DataGrid1.RowHeight * 2

Exit For

End If

Next

End Sub


AllowUpdate Property

See Also	Applies To

Returns or sets a value indicating whether a user can modify any data in the DBGrid control.

Syntax

object.AllowUpdate [= value]

The AllowUpdate property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether the user can change data, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	The user can modify data in the DBGrid control.

False	The user can't modify data in the DBGrid control.

Remarks

When the AllowUpdate property is False, the user can still scroll through the DBGrid control and select data, but can't change any of the values; any attempt to change the data in the grid is ignored.

You can also use the Column object properties to make individual columns of the DBGrid control read-only, but the AllowUpdate property setting takes precedence over the column settings (without changing the column settings).

Note   The Recordset object may not enable updates even if AllowUpdate is True for the DBGrid control; in this case a trappable error occurs when the user tries to change the record.


See Also

AllowAddNew Property

AllowDelete Property

Data Control

Locked Property


AllowUpdate Property Applies To

DBGrid Control


ColIndex Property

See Also	Applies To

Returns or sets a value indicating the position of the column in the Columns collection of the DBGrid control and the visible position (left-to-right) of the column in the DBGrid control.

Syntax

object.ColIndex [= value]

The ColIndex property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer ranging from 0 (the column furthest to the left) to the setting of the Count property.

Remarks

You can reorder columns by changing the value of the ColIndex property.  Setting ColIndex to 0 places the column in the leftmost position and all the ColIndex property settings of the columns formerly to the left of this column are incremented.

Setting this property to the same setting as the Count property of the Columns collection of the DBGrid control places the column at the rightmost position and all the ColIndex property settings of columns formerly to the right of this column are decremented.

Setting this property to a number, n, between 0 and the setting of the Count property of the Columns collection of the DBGrid control places the column to the left of the column that was formerly in the position represented by n, and all columns between the rearranged column's old position and n are adjusted accordingly.


See Also

Count Property

Column Object, Columns Collection

Col, Row Properties

Data Control

DBGrid Control


ColIndex Property Applies To

Column Object


ColumnHeaders Property

See Also	Applies To

Returns or sets a value indicating whether the column headers are displayed in a DBGrid control.

Syntax

object.ColumnHeaders [= value]

The ColumnHeaders property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines whether column headers are displayed, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	DBGrid control's column headers are displayed.

False	DBGrid control's column headers aren't displayed.


See Also

Column Object, Columns Collection

Columns Property

Data Control


ColumnHeaders Property Applies To

DBGrid Control


Columns Property (DBGrid)

See Also	Applies To

Returns a collection of Column objects.

Syntax

object.Columns

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The Columns property setting is a String or Variant.

You can manipulate most of a DBGrid control's attributes by changing the properties of Column objects.  Choose a specific Column object with the Col property.


See Also

Col, Row Properties

Column Object, Columns Collection

Data Control

Add Method (DBGrid)

Remove Method


Columns Property Applies To

DBGrid Control


DefColWidth Property

See Also	Applies To

Returns or sets a value indicating the default column width for all columns in the DBGrid control.

Syntax

object.DefColWidth [= value]

The DefColWidth property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer based on the scale mode of the control.

Remarks

If you set the DefColWidth property to 0, the control automatically sizes all columns based on either the width of the column heading or the Size property setting of the underlying field, whichever is larger.  For example, to set the default column width to the width of the first column:

DataGrid1.DefColWidth = DataGrid1.Columns(0).Width


See Also

AllowRowSizing Property

Column Object, Columns Collection

Data Control

Field Object, Fields Collection

Size Property


DefColWidth Property Applies To

DBGrid Control


DividerStyle Property

See Also	Example	Applies To

Returns or sets a value specifying the style of border drawn on the right edge of the selected column of a DBGrid control.

Syntax

object.DividerStyle [= value]

The DividerStyle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer that specifies the border style, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	No divider.

1	(Default) Black line.

2	Dark gray line.

3	Raised.

4	Inset.

5	Divider is drawn using the color set by the ForeColor property.

Remarks

The DividerStyle property doesn't affect whether the border can be dragged or not.  When the border is either raised or inset, the colors used are set by Microsoft Windows.


See Also

Data Control

RowDividerStyle Property


DividerStyle Property Applies To

Column Object


DividerStyle Property Example

This example changes the  column divider style when the user clicks a heading.

Private Sub DataGrid1_HeadClick (ColIndex As Long)

If DataGrid1.RowDividerStyle <> 5 Then

DataGrid1.Columns(ColIndex).DividerStyle = _

 DataGrid1.Columns(ColIndex).DividerStyle + 1

Else

DataGrid1.Columns(ColIndex).DividerStyle = 0

End If

End Sub


FirstRow Property

See Also	Applies To

Returns or sets a value containing the bookmark for the first visible row in the DBGrid control.  Not available at design time.

Syntax

object.FirstRow [= value]

The FirstRow property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression containing a bookmark corresponding to the first visible row in the DBGrid control.

Remarks

Setting the FirstRow property causes the DBGrid control to scroll so that the specified row is the topmost row in the DBGrid control.


See Also

RowBookmark Method


FirstRow Property Applies To

DBGrid Control


HeadBackColor Property

See Also	Example	Applies To

Returns or sets a value indicating the background color of the selected column of the DBGrid control.

Syntax

object.HeadBackColor [= color]

The HeadBackColor property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

color	A value or constant that determines the background or foreground colors of an object, as described in Settings.

Settings

Visual Basic uses the Microsoft Windows operating environment red-green-blue (RGB) color scheme.  The settings for color are:

Setting	Description

Normal RGB colors	Colors specified by using the Color palette or by using the RGB or QBColor function in code.

System default colors	Colors specified by system color constants listed in the Visual Basic (VB) object library in the Object Browser. The default setting is vbButtonFace.  The Windows operating environment substitutes the user's choices as specified in the Control Panel settings.

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 settings and listed in the Visual Basic (VB) object library in the Object Browser.


See Also

BackColor Property

Data Control

HeadForeColor Property


HeadBackColor Property Applies To

Column Object


HeadBackColor, HeadForeColor Properties Example

This example displays the Color Common dialog box and sets the BackColor and ForeColor properties of the current column.  It also sets the HeadBackColor and HeadForeColor properties to the reverse combination.

Sub ReSetColors ()

CMDialog1.DialogTitle = "Column BackColor"

CMDialog1.Action = 3	' Display Color dialog box.

DataGrid1.Columns(DataGrid1.ColIndex).BackColor = CMDialog1.Color

DataGrid1.Columns(DataGrid1.ColIndex).HeadForeColor = _

 CMDialog1.Color

CMDialog1.DialogTitle = "Column ForeColor"

CMDialog1.Action = 3	' Bring up color dialog box.

DataGrid1.Columns(DataGrid1.ColIndex).ForeColor = CMDialog1.Color

DataGrid1.Columns(DataGrid1.ColIndex).HeadBackColor = _

 CMDialog1.Color

End Sub


HeadFont Property

See Also	Applies To

Returns or sets a value indicating the font used in column headers in a DBGrid control.

Syntax

object.Type [= value]

The Type property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An object expression that evaluates to a Font object.  The default value is the column's current font set to bold.

Remarks

Changing the HeadFont property may resize the headers to accommodate the new font.


See Also

Column Object, Columns Collection

Data Control

DefColWidth Property

Font Object

Font Property


HeadFont Property Applies To

DBGrid Control


HeadForeColor Property

See Also	Example	Applies To

Returns or sets a value indicating the foreground color of the selected column in a DBGrid control.

Syntax

object.HeadForeColor [= color]

The HeadForeColor property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

color	A value or constant that determines the background or foreground colors of an object, as described in Settings.

Settings

Visual Basic uses the Microsoft Windows operating environment red-green-blue (RGB) color scheme.  The settings for color are:

Setting	Description

Normal RGB colors	Colors specified by using the Color palette or by using the RGB or QBColor function in code.

System default colors	Colors specified by system color constants listed in the Visual Basic (VB) object library in the Object Browser.  The default setting is vbButtonFace.  The Windows operating environment substitutes the user's choices as specified in the Control Panel settings.

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 listed in the Visual Basic (VB) object library in the Object Browser.


See Also

Column Object, Columns Collection

Data Control

ForeColor Property

HeadBackColor Property


HeadForeColor Property Applies To

DBGrid Control


HeadLines Property

See Also	Example	Applies To

Returns or sets a value indicating the number of lines of text displayed in the DBGrid control headers.

Syntax

object.HeadLines [= value]

The HeadLines property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A single from 0 to 10.  The default value is 1, which causes the control to displays the names of underlying fields for each column in the header.  A setting of 0 removes the headings

Remarks

The HeadLines property can be used to display more than one line of text above the columns in the DBGrid control.

You can override the default setting (1) by setting the Caption property for each column explicitly.


See Also

Column Object, Columns Collection

Columns Property

Data Control

DefColWidth Property

HeadBackColor Property

HeadForeColor Property


HeadLines Property Applies To

DBGrid Control


HeadLines Property Example

This example checks the value of a check box to determine whether or not to display headings in the grid.

Private Sub Check1_Click ()

If Check1.Value = vbChecked Then	' If checked,

DataGrid1.HeadLines = 2	' two lines in headings.

Else

DataGrid1.HeadLines = 0	' No headings.

End If

End Sub


NumberFormat Property

See Also	Example	Applies To

Returns or sets a value indicating the format string for the Column object of a DBGrid control.

Syntax

object.NumberFormat [= value]

The NumberFormat property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that defines how the expression in the Value property is formatted.  The default value is a zero-length string ("").

Remarks

The Text property is derived from this format that is applied to the Value property.  If NumberFormat is set to an invalid string, data in the cells are displayed as #ERR# and the value set in the Value property remains unchanged.  See the Format function for information about valid format strings.


See Also

Column Object, Columns Collection

Data Control

Format Function

Text Property

Value Property


NumberFormat Property Applies To

Column Object


NumberFormat Property Example

This example adds a new field to the database and then adds a new column.

Private Sub Command1_Click ()

Dim MyDB As Database, Fd Field, NewCol As Integer

Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open a database.

Set Fd = MyDB.TableDefs!Authors.CreateField("Phone",dbText,15)

' Add field to TableDefs collection.

MyDB.TableDefs("Authors").Fields.Append Fd

NewCol = DataGrid1.Columns.Count	' Get new column number.

DataGrid1.Add NewCol	' Add new column to grid.

DataGrid1.Columns(NewCol).DataField = "Phone"

DataGrid1.Columns(NewCol).Visible = True	' Default is False.

DataGrid1.Columns(NewCol).Width = Fd.Size

DataGrid1.Columns(NewCol).NumberFormat = "(###) ###-####"

End Sub


RecordSelectors Property

See Also	Applies To

Returns or sets a value indicating if record selectors are displayed in the DBGrid control.

Syntax

object.RecordSelectors [= value]

The RecordSelectors property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A Boolean expression that determines if record selectors are displayed, as described in Settings.

Settings

The settings for value are:

Setting	Description

True	Record selectors are displayed in the DBGrid control.

False	Record selectors aren't displayed DBGrid control.

Remarks

Record selectors, when displayed, appear to the left of the rows in the DBGrid control.  When the user selects the record selector, the entire record (row of the DBGrid control) is selected.


See Also

Column Object, Columns Collection

Data Control

SelBookmarks Property

SelEndCol, SelStartCol Properties


RecordSelectors Property Applies To

DBGrid Control


RowDividerStyle Property

See Also	Example	Applies To

Returns or sets a value that specifies the style of border drawn between the rows of the selected DBGrid control.

Syntax

object.RowDividerStyle [= value]

The RowDividerStyle property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer that specifies the border style, as described in Settings.

Settings

The settings for value are:

Setting	Description

0	No divider.

1	Black line.

2	(Default) Dark gray line.

3	Raised.

4	Inset.

5	Divider is drawn using the ForeColor property setting color.

Remarks

The RowDividerStyle property doesn't affect whether the border can be dragged or not.  When the border is raised or inset, Microsoft Windows sets the colors.


See Also

Column Object, Columns Collection

Data Control

DividerStyle Property


RowDividerStyle Property Applies To

DBGrid Control


RowDividerStyle Property Example

This example toggles through the different row line styles when you click a command button.

Private Sub ChangeStyle_Click ()

If DataGrid1.RowDividerStyle < 5 Then

DataGrid1.RowDividerStyle = DataGrid1.RowDividerStyle + 1

Else

DataGrid1.RowDividerStyle = 0

End If

End Sub


SelBookmarks Property

See Also	Example	Applies To

Returns a collection of bookmarks for all selected records in the DBGrid control.

Syntax

object.SelBookmarks

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

When a record is selected in the DBGrid control, its bookmark is appended to the collection returned by the SelBookmarks property.  For example, if you create a clone of the Recordset object created by the DBGrid control, you can process individual data records by repositioning the cloned Recordset with bookmarks taken from the SelBookmarks collection.


See Also

Add Method (DBGrid)

Bookmark Property

Data Control

Recordset Object, Recordsets Collection

Remove Method

SelBookmarks Collection


SelBookmarks Property Applies To

DBGrid Control


SelBookmarks Property Example

This example loops through the rows the user has selected and deletes them from the database.

Private Sub DeleteRows_Click ()

Do While DataGrid1.SelBookmarks.Count <> 0

Data1.Recordset.Bookmark = DataGrid1.SelBookmarks(0)

Data1.Recordset.Delete

Loop

End Sub


VisibleCols Property

See Also	Example	Applies To

Returns or sets a value indicating the number of visible columns in the DBGrid control.  Not available at design time.

Syntax

object.VisibleCols [= value]

The VisibleCols property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	An integer ranging from 0 to the setting of the Cols property of the DBGrid control.

Remarks

The VisibleCols property includes either fully or partially visible DBGrid control columns.


 VisibleCols Property Applies To

DBGrid Control


See Also

Data Control

Visible Property

VisibleRows Property


VisibleCols Property Example

'This example defines buttons to move the grid a whole page left or right.

Private Sub PageRight_Click ()

'Page grid to the right.

If DataGrid1.LeftCol + DataGrid1.VisibleCols < _

 DataGrid1.Columns.Count Then

DataGrid1.LeftCol = DataGrid1.LeftCol + _

 DataGrid1.VisibleCols

End If

End Sub

Private Sub PageLeft_Click ()

'Page grid to the left.

If DataGrid1.LeftCol - DataGrid1.VisibleCols >= 0 Then

DataGrid1.LeftCol = DataGrid1.LeftCol - _

 DataGrid1.VisibleCols

End If

End Sub


VisibleRows Property

See Also	Example	Applies To

Returns a value indicating the number of visible rows in the DBGrid control.

Syntax

object.VisibleRows

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The VisibleRows property returns an integer ranging from 0 to the setting of the Rows property of the DBGrid control.  The VisibleRows property includes either fully or partially visible DBGrid control rows.


See Also

Data Control

RowHeight Property

Visible Property

VisibleCols Property


VisibleRows Property Applies To

DBGrid Control


VisibleRows Property Example

This example selects all the rows that are currently visible on the grid.

Private Sub SelectVisible_Click ()

Dim I

For I = 0 To DataGrid1.VisibleRows - 1

DataGrid1.SelBookmarks.Add DataGrid1.RowBookmark(I)

Next I

End Sub


BoundColumn Property

See Also	Applies To

Returns or sets the name of the source field in a Recordset object that is used to supply a data value to another Recordset, or the name of the field used to fill a DBList or DBCombo control.

Syntax

object.BoundColumn [= value]

The BoundColumn property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies the name of a field in the Recordset created by the Data control specified by the RowSource property.

Remarks

Generally, when working with the DBList and DBCombo controls, you use two Data controls; one to fill the list as designated by the RowSource property.  The ListField property designates the field used to fill the list.  The second Data control, as designated by the DataSource property, manages a Recordset containing a field to be updated.  Once the user chooses one of the items in the list, the data from the RowSource recordset's BoundColumn field is passed to the field in the second Data control, as designated by the DataSource and DataField properties.  This way you can designate one field to fill the list, and another field (from the same Recordset) to pass as data to the Recordset designated by the DataSource and DataField properties when an item is selected.

If the ListField property is not provided, the field specified by the BoundColumn property is also used to fill the control's list.

If the field specified by the BoundColumn property can't be found in the Recordset, a trappable error occurs.

By using two Data controls, one to fill the list and another to manage the Recordset to be updated, you can create a list of values that doesn't necessarily match the values passed to the updated record.  For example, you can specify a description field to fill the list, and use a coded number that corresponds to that description to update the bound record.


See Also

ComboBox Control

Data Control

Implementing the DBList and DBCombo Controls

ListBox Control

ListField Property

Recordset Object, Recordsets Collection

RecordSource Property


BoundColumn Property Applies To

DBCombo Control

DBList Control


ListField Property

See Also	Applies To

Returns or sets the name of the field in the Recordset object used to fill the DBCombo or DBList control's list portion.

Syntax

object.ListField [= value]

The ListField property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies the name of a field in the Recordset created by the Data control specified by the RowSource property.

Remarks

The ListField property enables you to select which field in the Recordset is used to fill the list portion of the control.  This property is used in conjunction with the RowSource property that specifies which Data control is used to create the Recordset used to fill the list.  If the ListField property is not provided, the BoundColumn property is used to specify the field in the Recordset used to fill the list.

Generally, you use two Recordset objects with the data-aware list controls.  One Recordset contains a read-only list of valid selections, while the other Recordset is updated with selections from the list.  For example, the DBList control could be generated from a query that returned a list of valid part numbers and their descriptions.  The ListField property would point to the description field of the Recordset, so that the user doesn't see the actual part numbers.  The BoundColumn property would point to the part number field, as this is what needs to be updated in the Recordset.

If the field specified by the ListField property can't be found in the Recordset, a trappable error occurs.

If the ListField property is not provided, the BoundColumn property is used to fill the list.  If neither of these two properties are provided when the control is refreshed, the list is empty.


See Also

ComboBox Control

Data Control

Implementing the DBList and DBCombo Controls

ListBox Control

RecordSource Property

RowSource Property

Recordset Object, Recordsets Collection


ListField Property Applies To

DBCombo Control

DBList Control


RowSource Property

See Also	Applies To

Sets a value that specifies the Data control from which the DBList and DBCombo controls' list is filled. Not available at run time.

Remarks

To fill the list in a DBCombo or DBList control, you must specify a Data control in the RowSource property at design time using the Properties window.

To complete the connection with a field in the Recordset object managed by the Data control, you must also provide the name of a Field object in the ListField or BoundColumn properties.  Unlike the ListField  property, the RowSource property setting isn't available at run time.


See Also

BoundColumn Property

ComboBox Control

Data Control

Implementing the DBList and DBCombo Controls

ListField Property

ListBox Control

RecordSource Property

Recordset Object, Recordsets Collection


RowSource Property Applies To

DBCombo Control

DBList Control


SelectedItem Property

See Also	Applies To

Returns a value containing a bookmark for the selected record in a DBCombo control.

Syntax

object.SelectedItem

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

When you select an item in the list portion of the DBCombo control, the SelectedItem property contains a bookmark that you can use to reposition to the selected record in the Recordset as specified by the RowSource property.


See Also

Bookmark Property

Data Control

DBList Control

Implementing the DBList and DBCombo Controls

Recordset Object, Recordsets Collection


SelectedItem Property Applies To

DBCombo Control


VisibleItems Property

See Also	Applies To

Returns an array of bookmarks, one for each visible item in the DBCombo or DBList control's list.

Syntax

object.VisibleItems

The object  placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

These bookmarks may be used to fetch individual records from the Recordset used to fill the list.


See Also

Data Control

Implementing the DBList and DBCombo Controls

VisibleCount Property


VisibleItems Property Applies To

DBCombo Control

DBList Control


VisibleCount Property

See Also	Applies To

Returns a value indicating the number of visible items in the DBCombo or DBList control.

Syntax

object.VisibleCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The VisibleCount property returns an integer from 0 to the number of items visible in the control.  An item is considered visible even if only a portion of the text is visible, as when the IntegralHeight property setting is False.


See Also

Data Control

Implementing the DBList and DBCombo Controls

IntegralHeight Property

VisibleItems Property


VisibleCount Property Applies To

DBCombo Control

DBList Control


MatchedWithList Property

Applies To

Returns True if the current contents of the BoundText property matches one of the records in the list portion of the control.

Syntax

object.MatchedWithList

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The MatchedWithList property return values are:

Value	Description

True	The contents of the BoundText property matches one of the records in the list.

False	The contents of the BoundText property does not match any of the records in the list.

Remarks

When you enter a value in the text portion of the DBCombo control, the MatchedWithList property is set to True if the value entered is one of the items shown in the list.  Using this property, your code can trap entries not in the list, or provide code to add the new entry to the source table.


 MatchedWithList Property Applies To

DBCombo Control

DBList Control


BoundText Property

See Also	Applies To

Returns or sets the value of the BoundColumn property of a DBCombo or DBList control passed from or to the DataField property after a selection is made.

Syntax

object.BoundText [= value]

The BoundText property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A string expression that specifies a data value.

Remarks

After a user makes a selection with a DBList or DBCombo control, the BoundText property contains the data contents of the BoundColumn field.  Typically, the list portion of the control is built based on a database query.  When an item in the list is selected, the item becomes available to the Data control specified by the DataSource property.  The selection also appears in the text box portion of the control where it can be edited.  If the user enters a value in the text box portion, the list portion attempts to position to a matching item.  If a match is found, the BoundText property value is set, based on the field specified by the BoundColumn property.  If no match is found, the BoundText property is set to Null.


See Also

DBCombo Control

DBList Control

ComboBox Control

Data Control

Implementing the DBList and DBCombo Controls

ListBox Control

ListField Property

Recordset Object, Recordsets Collection

RecordSource Property


 BoundText Property Applies To

DBCombo Control

DBList Control


Recordset Property Example

This example uses a Data control to create a Recordset object containing all Titles published in 1994.  The Recordset object created is accessible by referencing the Recordset property of the Data control.

Dim Rs As Recordset

Data1.Database = "BIBLIO.MDB"

Data1.RecordSource =  _

"Select * From TITLES where [Year Published] = 1994"

Data1.Refresh

Set Rs = Data1.Recordset

If Rs.RecordCount > 0 Then

Do Until Rs.EOF

Debug.Print Rs("Title")

Rs.MoveNext

Loop

Else

MsgBox "No titles in 1994."

End If


Exclusive Property Example

This 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


Database, DatabaseName Properties Example

This example examines the Database property of a data control and prints the name of each Table in the Debug window.

Sub PrintTableNames ()

Dim Td As TableDef

Data1.DatabaseName = "BIBLIO.MDB"	' Set database file.

Data1.Refresh	' Open the Database.

' Read and print the name of each table in the database.

For Each Td in Data1.Database.TableDefs

Debug.Print Td.Name

Next

End Sub


LastModified Property Example

This example might be used with a menu in a program to enable users to return to the last record that was modified.

Data1.Recordset.Bookmark = Data1.Recordset.LastModified


DataChanged Property and Validate Event Example

This 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 doesn't enable changes to the Au_ID field, which is bound to Text1.

Private 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	' Don't save changed data.

End If

...

End Sub


RecordsetType Property Example

This example uses the Data control to create a Recordset object and examines the Data control's RecordsetType and the Type property of the created Recordset object to determine what type of recordset was created.

Function NewRecordsetType() As Integer

Data1.Recordset.Close	' Close existing Recordset.

' Indicate type of Recordset wanted.

Data1.RecordsetType = vbRSTypeDynaset

Data1.DatabaseName = "MYDB.MDB"

Data1.RecordSource = "MyTable"

Data1.Refresh

Select Case Data1.Recordset.Type

Case dbOpenTable Debug.print "Table-type Recordset created."

Case dbOpenDynaset Debug.print "Dynaset-type Recordset created."

Case dbOpenSnapshot Debug.print "Snapshot-type Recordset created."

End Select

Select Case Data1.RecordsetType

Case vbRSTypeTable Debug.print "Table-type Recordset created."

Case vbRSTypeDynaset Debug.print "Dynaset-type Recordset created."

Case vbRSTypeSnapshot Debug.print "Snapshot-type Recordset created."

End Select


Data Access Constants

See Also

You can use the Object Browser to browse the list of built-in constants.  From the View menu, choose Object Browser, select the appropriate library, and then select the Constants object. Scroll the list in the Methods/Properties box to see the complete list of constants.

The data access objects provide built-in constants that you can use with methods or properties.  These constants all begin with the letters db and are documented with the method or property to which they apply.

Visual Basic contains built-in constants that you can use with methods or properties.  These constants all begin with the letters vb and are documented with the method or property to which they apply.

Data Access Object Constants

Data Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants


See Also

Visual Basic Constants

Visual Basic for Applications Constants


Data Access Object Constants

See Also

Recordset.Type Property Constants

Constant	Value	Description

dbOpenTable 	1	Open table-type Recordset.

dbOpenDynaset 	2	Open dynaset-type Recordset.

dbOpenSnapshot	4	Open snapshot-type Recordset.

OpenRecordset Method options Argument Constants

Constant	Value	Description

dbDenyWrite	1	Other users can't change dynaset records.

dbDenyRead	2	Other users can't read dynaset records.

dbReadOnly	4	Open dynaset as read-only.

dbAppendOnly	8	You can add new records to the dynaset, but you can't read existing records.

dbInconsistent	16	Updates apply to all dynaset fields, even if other records affected.

dbConsistent	32	Updates apply only to those fields that will not affect other records in the dynaset.

dbSQLPassThrough	64	Sends an SQL statement to an ODBC database.

dbFailOnError	128	Roll back changes if error occurs.

dbForwardOnly	256	Create forward-only scrolling snapshot-type Recordset.

dbOptionINIPath	1	Set application initialization (.INI) filename and path .

Attributes Property Constants

Field.Attributes Property

Constant	Value	Description

dbFixedField     	1	Field size fixed (default for Numeric fields).

dbVariableField  	2	Field size variable (Text fields only).

dbAutoIncrField  	16	New record field value incremented to unique Long integer (counter type).

dbUpdatableField 	32	Field is updatable (read/write).

dbDescending	1	Field sorted in descending order.

Type Property Constants (Field.Type, Parameter.Type, and Property.Type Properties)

Constant	Value	Description

dbBoolean	1	Boolean (True/False) data.

dbByte	2	Byte (8-bit) data .

dbInteger	3	Integer data.

dbLong	4	Long Integer data.

dbCurrency	5	Currency data.

dbSingle	6	Single-precision floating-point data.

dbDouble	7	Double-precision floating-point data.

dbDate	8	Date value data.

dbText	10	Text data (variable width).

dbLongBinary	11	Binary data (bitmap).

dbMemo	12	Memo data (extended text).

Relation.Attributes Property Constants

Constant	Value	Description

dbRelationUnique	1	One-to-one relationship.

dbRelationDontEnforce 	2	Relationship not enforced (no referential integrity).

dbRelationInherited 	4	Relationship exists in a noncurrent database containing the two attached tables.

dbRelationUpdateCascade 	256	Updates cascade.

dbRelationDeleteCascade 	4096	Deletions cascade.

dbRelationLeft	16777216	Relationship is a left join.

dbRelationRight  	33554432	Relationship is a right join.

TableDef.Attributes Property Constants

Constant	Value	Description

dbAttachExclusive  	65536	Attached Microsoft Jet database engine table opened for exclusive use.

dbAttachSavePWD 	131072	Save user ID and password for attached table.

dbSystemObject 	2147483650	System table.

dbHiddenObject  	1	Hidden table (for temporary use).

dbTable	1	Table object.

dbQueryDef	5	QueryDef object.

dbAttachedTable  	1073741824	Attached non-ODBC database table.

dbAttachedODBC 	536870912	Attached ODBC database table.

QueryDef.Type Property Constants

Constant	Value	Description

dbQSelect	0	SELECT query.

dbQAction	240	Action query.

dbQCrosstab	16	Crosstab query.

dbQDelete	32	DELETE query.

dbQUpdate	48	UPDATE query.

dbQAppend	64	APPEND query.

dbQMakeTable	80	Make-table query.

dbQDDL	96	Data definition language (DDL) query.

dbQSQLPassThrough	112	SQL pass-through query.

dbQSetOperation	128	Set operation query.

dbQSPTBulk	144	Bulk operation query.

CompactDatabase, CreateDatabase Methods options Argument Constants

Constant	Value	Description

dbVersion10	1	Microsoft Jet database engine version 1.0.

dbEncrypt	2	Encrypt database.

dbDecrypt	4	Decrypt database while compacting.

dbVersion11	8	Microsoft Jet database engine version 1.1.

dbVersion20	16	Microsoft Jet database engine version 2.0/2.5.

dbVersion30	32	Microsoft Jet database engine version 3.0.

Container.Permissions Property

Constant	Value	Description

dbSecNoAccess	0	No access to the object.

dbSecFullAccess	1048575	Has full access to the object.

dbSecDelete 	65536	Can delete the object.

dbSecReadSec 	131072	Can read the object's security-related information.

dbSecWriteSec 	262144	Can alter access permissions.

dbSecWriteOwner 	524288	Can change the Owner property setting.

Databases Container.Permissions Property Constants

Constant	Value	Description

dbSecDBCreate	1	Can create new databases (valid only on the databases Container object in the system database, typically SYSTEM.MDW).

dbSecDBOpen	2	Can open the database.

dbSecDBExclusive	4	Has exclusive access.

Tables Container.Permissions Property Constants

Constant	Value	Description

dbSecCreate	1	Create new tables (valid only with a Container object that represents a table).

dbSecReadDef	4	Read the table definition, including column and index information.

dbSecWriteDef	8	Modify or delete table definition, including column and index information.

dbSecRetrieveData 	16	Retrieve data from the document.

dbSecInsertData	32	Add records.

dbSecReplaceData	64	Modify records.

dbSecDeleteData	128	Delete records.

EditMode Property Constants

Constant	Value	Description

dbEditNone	0	No editing operation in effect.

dbEditInProgress	1	Edit method invoked.

dbEditAdd	2	AddNew method invoked.

CollatingOrder Property Constants

Constant	Value	Description

dbSortArabic	267	Arabic collating order.

dbSortCyrillic	263	Russian collating order.

dbSortCzech	264	Czech collating order.

dbSortDutch 	259	Dutch collating order.

dbSortGeneral	256	English, German, French, and Portuguese collating order.

dbSortGreek	269	Greek collating order.

dbSortHebrew	268	Hebrew collating order.

dbSortHungarian	265	Hungarian collating order.

dbSortIcelandic	262	Icelandic collating order.

dbSortJapanese	1041	Japanese collating order.

dbSortNeutral	1024	Neutral collating order.

dbSortNorw	261	Norwegian and Danish collating order.

dbSortPDXIntl	4096	Paradox international collating order.

dbSortPDXNor	4098	Paradox Norwegian and Danish collating order.

dbSortPDXSwe	4097	Paradox Swedish and Finnish collating order.

dbSortPolish	266	Polish collating order.

dbSortSpanish	258	Spanish collating order.

dbSortSwedFin	260	Swedish and Finnish collating order.

dbSortTurkish	270	Turkish collating order.

dbSortUndefined	-1	Collating order undefined or unknown.

CompactDatabase, CreateDatabase Methods locale Argument Constants

Constant	Value	Description

dbLangArabic	LANGID0x0401CP1256COUNTRY0	Arabic collating order.

dbLangCzech	LANGID0x0405CP1250COUNTRY0	Czech collating order.

dbLangDutch	LANGID0x0413CP1252COUNTRY0	Dutch collating order.

dbLangGeneral	LANGID0x0409CP1252COUNTRY0	English, German, French, Portuguese, Italian, and Modern Spanish collating order.

dbLangGreek	LANGID0x0408CP1253COUNTRY0	Greek collating order.

dbLangHebrew	LANGID0x040DCP1255COUNTRY0	Hebrew collating order.

dbLangHungarian	LANGID0x040ECP1250COUNTRY0	Hungarian collating order.

dbLangIcelandic	LANGID0x040FCP1252COUNTRY0	Icelandic collating order.

dbLangNordic	LANGID0x041DCP1252COUNTRY0	Nordic collating order.

dbLangNorwdan	LANGID0x0414CP1252COUNTRY0	Norwegian and Danish collating order.

dbLangPolish	LANGID0x0415CP1250COUNTRY0	Polish collating order.

dbLangCyrillic	LANGID0x0419CP1251COUNTRY0	Russian collating order.

dbLangSpanish	LANGID0x040ACP1252COUNTRY0	Spanish collating order.

dbLangSwedfin	LANGID0x040BCP1252COUNTRY0	Swedish and Finnish collating order.

dbLangTurkish	LANGID0x041FCP1254COUNTRY0	Turkish collating order.

Idle Method Argument Constants

Constant	Value	Description

dbFreeLocks	1	Free page locks.

Synchronize Method ExchgType Argument Constants

Constant	Value	Description

dbRepExportChanges	1	Synchronizes the target database replica with the current database.

dbRepImportChanges	2	Synchronizes the current database with the target database replica.

dbRepImpExpChanges	4	Bidirectionally synchronizes the current database with the target database replica.

CreateReplica Method Options Argument Constants

Constant	Value	Description

dbRepMakeReadOnly	2	The replicable elements of the newly-created database will not be modifiable.


See Also

Data Control Constants

DBGrid Control Constants

DBList and DBCombo Control Constants


Data Control Constants

See Also

Error Event Constants

Constant	Value	Description

vbDataErrContinue	0	Continue.

vbDataErrDisplay	1	(Default) Display the error message.

EditMode Property Constants

Constant	Value	Description

vbDataEditNone	0	No editing operation in progress.

vbDataEditMode	1	Edit method invoked; current record in copy buffer.

vbDataEditAdd	2	AddNew method invoked; current record hasn't been saved.

Options Property Constants

Constant	Value	Description

vbDataDenyWrite	1	Other users can't change records in recordset.

vbDataDenyRead	2	Other users can't read records in recordset.

vbDataReadOnly	4	No user can change records in recordset.

vbDataAppendOnly	8	New records can be added to the recordset, but existing records can't be read.

vbDataInconsistent	16	Updates can apply to all fields of the recordset.

vbDataConsistent	32	Updates apply only to those fields that will not affect other records in the recordset.

vbDataSQLPassThrough	64	Sends an SQL statement to an ODBC database.

Validate Event Action Constants

Constant	Value	Description

vbDataActionCancel	0	Cancel the operation when the Sub exits.

vbDataActionMoveFirst	1	MoveFirst method.

vbDataActionMovePrevious	2	MovePrevious method.

vbDataActionMoveNext	3	MoveNext method.

vbDataActionMoveLast	4	MoveLast method.

vbDataActionAddNew	5	AddNew method.

vbDataActionUpdate	6	Update operation (not UpdateRecord).

vbDataActionDelete	7	Delete method.

vbDataActionFind	8	Find method.

vbDataActionBookmark	9	The Bookmark property is set.

vbDataActionClose	10	Close method.

vbDataActionUnload	11	The form is being unloaded.

Beginning-of-File Constants

Constant	Value	Description

vbMoveFirst	0	Move to first record.

vbBOF	1	Move to beginning of file.

End-of-File Constants

Constant	Value	Description

vbMoveLast	0	Move to last record.

vbEOF	1	Move to end of file.

vbAddNew	2	Add new record to end of file.

Recordset-Type Constants

Constant	Value	Description

vbRSTypeTable	0	Table-type recordset.

vbRSTypeDynaset	1	Dynaset-type recordset.

vbRSTypeSnapShot	2	Snapshot-type recordset.


See Also

Data Access Object Constants


DBList and DBCombo Controls Constants

See Also

Appearance Constants

Constant	Value	Description

dblFlat	0	Flat appearance of DBList or DBCombo control.

dbl3D	1	Three-dimensional appearance of DBList or DBCombo control.

Area Constants (DBCombo only)

Constant	Value	Description

dbcAreaButton	0	Returns the location of the DBCombo control's button when a Click or Double-Click event occurs there.

dbcAreaEdit	1	Returns the location of the DBCombo control's text box when a Click or Double-Click event occurs there.

dbcAreaList	2	Returns the location of the DBCombo control's list box when a Click or Double-Click event occurs there.

Match Entry Constants

Constant	Value	Description

dblBasicMatching	0	Basic matching.

dblExtendedMatching	1	Extended matching.

MousePointer Constants

Constant	Value	Description

dblDefault	0	(Default) Shape determined by the object.

dblArrow	1	Arrow.

dblCross	2	Cross (cross-hair pointer).

dblIBeam	3	I-Beam.

dblIcon	4	Icon (small square within a square).

dblSize	5	Size (four-pointed arrow pointing north, south, east, and west).

dblSizeNESW	6	Size NE SW (double arrow pointing northeast and southwest).

dblSizeNS	7	Size N S (double arrow pointing north and south).

dblSizeNWSE	8	Size NW SE (double arrow pointing northwest and southeast).

dblSizeEW	9	Size E W (double arrow pointing east and west).

dblUpArrow	10	Up Arrow.

dblHourglass	11	Hourglass (wait).

dblNoDrop	12	No Drop.

dblArrowHourglass	13	Arrow and hourglass.

dblArrowQuestion	14	Arrow and question mark.

dblSizeAll	15	Size all (can be customized under Microsoft Windows NT 3.51)

dblCustom	99	Custom icon specified by the MouseIcon property.

Style Constants

Constant	Value	Description

dblDropdownCombo	0	Drop-down Combo.

dblSimpleCombo	1	Simple combo.

dblDropdownList	2	Drop-down list.


See Also

Data Access Object Constants

Data Control Constants


DBGrid Control Constants

See Also

Alignment Constants

Constant	Value	Description

dbgLeft	0	Left.

dbgRight	1	Right.

dbgCenter	2	Center.

dbgGeneral	3	General.

BorderStyle Constants

Constant	Value	Description

dbgNone	0	None.

dbgFixedSingle	1	FixedSingle.

DataMode Constants

Constant	Value	Description

dbgBound	0	Bound.

dbgUnbound	1	Unbound.

DividerStyle Constants

Constant	Value	Description

dbgNoDividers	0	NoDividers.

dbgBlackLine	1	BlackLine.

dbgDarkGrayLine	2	DarkGrayLine.

dbgRaised	3	Raised.

dbgInset	4	Inset.

dbgUseForeColor	5	UseForeColor.

RowDividerStyle Constants

Constant	Value	Description

dbgNoDividers	0	NoDividers.

dbgBlackLine	1	BlackLine.

dbgDarkGrayLine	2	DarkGrayLine.

dbgRaised	3	Raised.

dbgInset	4	Inset.

dbgUseForeColor	5	UseForeColor.

Scroll Bar Constants

Constant	Value	Description

dbgNone	0	None.

dbgHorizontal	1	Horizontal.

dbgVertical	2	Vertical.

dbgBoth	3	Both.

dbgAutomatic	4	Automatic.


See Also

Data Access Object Constants

Data Control Constants


Syntax error in number. (Error 2420)

A number was called for here; it is invalid.  This can occur if a non-numeric value is provided as part of the expression.


Syntax error in date. (Error 2421)

Date syntax incorrect.  This error occurs if you specify an invalid date.  For example, 9/31/94 is invalid (September has only 30 days).


Syntax error in string. (Error 2422)

You entered an expression that includes an invalid string.  Check the expression to make sure you entered it correctly.


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

The expression doesn't use delimiters correctly.  To reference the properties of data objects, it is recommended that you use the ."<name>" syntax.


Unknown name. (Error 2424)

You entered an expression that has a field or property name that can't be recognized.  Make sure the object exists, or check the expression to make sure you entered it correctly.


Unknown function name. (Error 2425)

You entered an expression with a function name that can't be recognized.  Make sure the function exists, or check the expression to make sure you entered it correctly.


Function isn't available in expressions. (Error 2426)

You have entered a function that can't be used in this expression.  The functions DoEvents, LBound, UBound, Spc, and Tab aren't available in expressions.


Object has no value. (Error 2427)

You entered an expression containing an identifier for an object that has no value.  (Objects may have a default property value or return a default member function.)

Check the expression to make sure you entered it correctly.


Invalid arguments used with domain function. (Error 2428)

You have entered an invalid argument in a domain function.  For information on the function's arguments, see Domain Aggregate Functions, and then choose the name of the function.


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 parentheses.  For example, to see if a value is one of a set of values, you could use the following 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 contains any of the above abbreviations, which represent Texas, California, and Washington.


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, specify the upper and lower limits of the range separated with the reserved word And.  For example, to test for a range of "A" to "C" code, you could use the following code:

WHERE MyField Between "A" And "C"


Syntax error (missing operator). (Error 2431)

The expression or statement was missing an operator.


Syntax error (comma). (Error 2432)

The expression or statement used a comma where it doesn't belong or was missing a comma to separate arguments.


Syntax error. (Error 2433)

The wording or punctuation of the command isn't correct.  It may be missing an operator or an operator specified may not exist.


Syntax error (missing operator). (Error 2434)

The expression or statement was missing an operator.


Extra ). (Error 2435)

You entered an expression that has too many closing parentheses.  Delete any parenthesis that doesn't have a matching opening parenthesis.


Missing ), ], or Item. (Error 2436)

You entered an expression that is missing a closing parenthesis, bracket, or vertical bar.  Check the expression to make sure you entered it correctly.


Invalid use of vertical bars. (Error 2437)

You entered an expression that has invalid vertical bars (|).  Check the expression to make sure you entered it correctly.


Syntax error. (Error 2438)

You entered an expression that has invalid syntax.  For example, an operand or operator may be missing, you may have entered an invalid character or comma, or you may have entered text without surrounding it by quotation marks (").  Check the expression to make sure you entered it correctly.


Wrong number of arguments used with function. (Error 2439)

You entered an expression that has a function with the wrong number of arguments.  Check the function to verify how many arguments it takes, or check the expression to make sure you entered it correctly.


IIF function without (). (Error 2440)

The IIf function requires parentheses around its arguments, as shown in the following example:

IIf( expr, truepart, falsepart )


Invalid use of parentheses. (Error 2442)

You entered an expression that has invalid parentheses.  For example, you may be trying to use the parentheses syntax for an identifier in a query.  In a query, you can use only the standard identifier syntax.


Invalid use of Is operator. (Error 2443)

The Is operator is used to determine if an expression is Null.  You can use the Is operator in an expression only with Null or Not Null.


Expression too complex. (Error 2445)

This expression is too complex for the Microsoft Jet database engine.  Try to simplify the expression.


Out of memory during calculation. (Error 2446)

The application doesn't have enough memory to complete the calculation.  Make sure you have enough RAM and a virtual swap file established.  You may need to terminate other programs, remove desktop wallpaper bitmaps, or remove unneeded TSR programs or device drivers to recover enough memory.


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

The expression doesn't use delimiters correctly.  To reference the properties of data objects, it is recommended that you use the ."<name>" syntax.


Can't set value. (Error 2448)

You are trying to assign a value to an object that is read-only or doesn't have a value.


The connection for viewing your attached Excel worksheet was lost. (Error 3620)

The connection for viewing your attached Excel worksheet was lost.  Check to see if the session of Excel has been terminated.


No country code found in connect string for an attached (or linked) table. (Error 3621)

Possible causes and solutions:

The field name you've specified might be misspelled.

Check the spelling of the field name.

You tried to update a Counter field, but Counter fields can't be updated.


No country code found in connect string for an attached (or linked) table. (Error 3622)

There was no country code found in the connect string to an attached (or linked) table.  Check the spelling of the field name to see if it was misspelled.


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.  Please contact Microsoft's product support services for more information.


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.

This error also occurs when you attempt to use mutually exclusive constants in an argument to a method, such as specifying both dbConsistent and dbInconsistent in the options argument to the OpenRecordset method.


Couldn't start session. (Error 3002)

You tried to initiate an operation that requires a new session, but you've reached the limit 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 start transaction; too many transactions already nested. (Error 3003)

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


'Database name' isn't a valid database name. (Error 3005)

The specified database name doesn't follow the standard naming conventions for filenames.  The name may be too long for the buffer that contains the path and filename.  Enter a new name, and then try the operation again.


Database 'name' 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.


Cant open library database 'name'. (Error 3007)
Can't open library database 'name'. (Error 3007)

The specified database is an internal Microsoft Jet engine library database, which you can't open.


Table 'name' is exclusively locked. (Error 3008)

You tried to use a table that is currently open for exclusive access by another user, or you tried to programmatically manipulate a table that is open through the user interface.  Address the appropriate condition, and then try the operation again.


Couldn't lock table 'name'; currently in use. (Error 3009)

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


Table 'name' 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 multi-user 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 roll back the deletion of your table.  To restore your table, the other user must first delete or rename the new table before you try the rollback operation again.


Couldn't find object 'name'. (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.


Object 'name' already exists. (Error 3012)

You tried to create an object with a name that already exists in this database.  Choose a different name, and then try the operation again.


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.


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 tables, and then try the operation again.


'Index name' isn't an index in this table. (Error 3015)

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


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 or changing the data type of the field.


The size of a field is too long. (Error 3017)

You tried to define or create a Text field longer than 254 characters.  Use a number between 1 and 254, and then try the operation again, or create a Memo field for the data.


Couldn't find field 'name'. (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].


Operation invalid without a current index. (Error 3019)

Set the Index, and then try the operation again.


Update or CancelUpdate without AddNew or Edit. (Error 3020)

You didn't use the AddNew or Edit method before trying to save changes to a record.  Use one of these methods, and then use the Update or CancelUpdate method.


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, when the underlying recordset contains no records or the record has been deleted.  Move to or select another record, and try the operation again.


Duplicate value in index, primary key, or relationship.  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.  Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try 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 the Rollback or Update method, and then use the AddNew or Edit method.


Couldn't find file 'name'. (Error 3024)

Possible causes:

The specified file doesn't exist.

You misspelled the filename.  Check for missing underscores ( _ ) or other punctuation, and make sure you didn't enter leading spaces.  The filename may be too long.  MS-DOS-based systems require filenames no longer than 8 characters with 3-character extensions separated by a period.


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 files, and then try the operation again.


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, compress your database, and then try the operation again.


Can't update.  Database or object 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 is defined as read-only in the operating system or by your network.

The database file is stored on read-only media.

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

When working with a secured database, databases, tables, or fields may be set to read-only.  You may not have permission to access this data with your user name and password.

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


Can't start your application.  The system database is missing or opened exclusively by another user. (Error 3028)

To ensure referential integrity in databases created by the Microsoft Jet database engine, your application must read the Microsoft Jet database's SYSTEM.MDW file.  Make sure the file is in the location specified in the SystemDB entry in the Registry.


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.


'Account name' 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.


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.


Can't perform this operation. (Error 3032)

Possible causes:

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 account, create a new account and add it to the group Admins, or add an existing account to the group Admins, and then delete the account.

You tried to put a user in a group to which the user already belongs, by appending either a Group object to a User object's Groups collection that already has a Group object of the same name, or a User object to a Group object's Users collection that already has a User object of the same name.


No permission for 'name'. (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.


Commit or Rollback without BeginTrans. (Error 3034)

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


Database has reached maximum size. (Error 3036)

To add data to this database, you must first reduce its size by deleting data.


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 table or query, and then try the operation again.


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.


Disk I/O error during read. (Error 3040)

The disk could not be read 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.


Can't open a database with a previous version of your application. (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 MS-DOS file handles. (Error 3042)

Either close some files, 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 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.


Disk or network error. (Error 3043)

An internal disk or drive failure prevents reading from or writing to the disk.

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.


'Path' isn't a valid path. (Error 3044)

Possible causes:

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.  Make sure the network is available, and then try the operation again.


Couldn't use 'name'; file already in use. (Error 3045)

The specified file is currently being used by another user or session.  Wait for the other user or session to finish working with the file, and then try the operation again.


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

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


Record is too large. (Error 3047)

You defined a table with records larger than can be supported.  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.


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 databases and try the operation again.


Can't open database 'name'.  It may not be a database that your application recognizes, or the file may be corrupt. (Error 3049)

Possible causes:

You tried to open a Btrieve, dBASE, or Paradox database or table.  Instead, attach (or link) the database or table to an existing Microsoft Jet database.

You tried to import or attach (or link) a Paradox database or table, and the associated .PX file couldn't be found.  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 Microsoft Jet database, it is 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.


Couldn't open file 'name'. (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 or query's creator.

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


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 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.


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.


Too many Memo or OLE object fields. (Error 3054)

You tried to perform a Btrieve operation that involves too many Memo or OLE object fields.  Reduce the number of Memo and OLE object fields, and then try the operation again.


Not a valid file name. (Error 3055)

You tried to use a filename that doesn't follow the naming conventions for your operating system.  Reenter the filename, and then try the operation again.


Couldn't repair this database. (Error 3056)

This database is corrupted or it isn't a Microsoft Jet database.  Restore the corrupted Microsoft Jet database from a backup copy or create a new database.


Operation not supported on attached, or linked, tables. (Error 3057)

Import data from the table, and then try the operation again.


Index or primary key can't contain a null value. (Error 3058)

Possible causes:

You tried to add a Null value to a primary key field.

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 put a Null value in a primary key field.


Operation canceled by user. (Error 3059)

You stopped the operation before its normal completion.  Some data changes may not have been saved.


Wrong data type for parameter 'parameter'. (Error 3060)

You tried to use an argument with a data type that conflicts with the data type defined for this parameter.  For example, you might have tried to use a string expression that expects a numeric argument with a parameter.  Use an argument that has the correct data type, and then try the operation again.


Too few parameters. Expected 'number'. (Error 3061)

This parameter query requires the specified number of parameters, which you didn't supply.  Provide the expected number of parameters, and run the query again.

In some cases, this message is generated when unknown field names or expressions are interpreted as query parameters.  Be sure to enclose field names containing spaces or punctuation with square brackets [].


Duplicate output alias 'name'. (Error 3062)

You tried to execute an SQL statement that has more than one alias with the same name.  The following statement, for example, would produce this error:

SELECT LastName AS Name, FirstName AS Name FROM Employees;

Rename one or more of the aliases, and then try the operation again.


Duplicate output destination 'name'. (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, SELECT...INTO, or UPDATE statement that lists the specified field name more than once.

Remove the duplicate fields or alias the output field names, and try the operation again.


Can't open action query 'name'. (Error 3064)

You tried to open an action query using the OpenQueryDef method, which is an obsolete method originally valid only with select queries.  The preferred method for executing an action query is to use the Execute method of the QueryDef.


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.  Select queries contain a SELECT statement and can return records; action queries do not.


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.


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.


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.


The action query 'name' cannot be used as a row source. (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 instead of the name of an action query as input to the FROM clause.


Can't bind name 'name'. (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; instead, you need to specify BIBLIO.MDB with OpenDatabase.


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.


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 can't 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 obsolete OpenQueryDef method on a query that is in a database opened for read-only access.

The database is read-only for one of the following reasons:

1.	You used the OpenDatabase function or Data Control, and opened the database for read-only access.

2.	The database file has been defined as read-only in MS-DOS or your network operating system.

3.	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.


Can't repeat table name 'name' 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.  If you are trying to join a table to itself, use an alias to change the second reference to the table.


'Message' in query expression 'expression'. (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.


'Name' 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.


'Message' 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.


Couldn't find input table or query 'name'. (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.


Ambiguous field reference 'reference'. (Error 3079)

The specified field reference could refer to more than one table listed in the FROM clause 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 OrderID

FROM Orders, [Order Details];

To complete this operation, fully qualify the field reference by adding a table name.  For example:

SELECT Orders.OrderID

FROM Orders, [Order Details];


Joined table 'name' not listed in FROM clause. (Error 3080)

Add the specified table name to the FROM clause of the query, and then try the operation again.


Can't join more than one table with the same name 'name'. (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.  If you are trying to join a table to itself, use a table alias to change the second reference to the table.


JOIN operation 'operation' 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.FirstName, 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.


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.


Can't insert data with 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.


Undefined function 'name' 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, that it can be used in SQL expressions, or check the expression to make sure you entered the name correctly.


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:

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

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

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

4.	In Visual Basic, you used the Data Control and set the ReadOnly property to True.

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


Too many expressions in GROUP BY clause. (Error 3087)

You created an SQL statement with more than 10 fields listed in the GROUP BY clause.  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 with more than ten expressions.  Remove some of the fields listed in the ORDER BY clause.


Too many expressions in DISTINCT output. (Error 3089)

You created an SQL statement that has an ALL, DISTINCT, or DISTINCTROW predicate with more than ten expressions.  Remove the DISTINCT reserved word, or remove some of the fields listed in the DISTINCT predicate.


Resultant table not allowed to have more than one Counter or Autonumber field. (Error 3090)

You tried to execute a query that would result in a table with more than one field that has a Counter or Autonumber data type.  Change the query to include only one Counter or Autonumber field.


Can't use HAVING clause in TRANSFORM statement. (Error 3092)

If you want to specify selection criteria, use a WHERE clause.


ORDER BY clause 'clause' conflicts with DISTINCT. (Error 3093)

You created an SQL statement with an ALL, DISTINCT, or DISTINCTROW predicate and an ORDER BY clause that contains a field not listed in the SELECT statement.  Remove the DISTINCT reserved word, or remove the specified field from the ORDER BY clause.


ORDER BY clause 'clause' 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.  Move the specified field to the left of the ungrouped fields, or remove the specified field from the ORDER BY clause.


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

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


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

You can't use an aggregate function in the WHERE clause of an SQL statement.


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

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


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

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


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

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


Can't set field 'name' 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.


There is no record in table 'name' with key matching field(s) 'name'. (Error 3101)

In a one-to-many relationship, you entered data on the "many" side for which there is no matching record on the "one" side.  For example, this error occurs if you join a Customers table and Orders table on a Customer ID field, and then add an order using a Customer ID that doesn't exist in the Customers table.


Circular reference caused by 'query reference'. (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.


Circular reference caused by alias 'name' in query definition's SELECT list. (Error 3103)

The specified alias created an unresolvable reference.  This error can occur, for example, 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;

SELECT week1 + week2 as hours, hours + overtime as gross, gross + ytdpay as week1

FROM EmployeePay


Can't specify Fixed Column Heading 'value' in a crosstab query more than once. (Error 3104)

When you create a crosstab query with 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.


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

Enter a destination field name in the specified statement, and then try the operation again.


Missing destination field name in UPDATE statement 'statement'. (Error 3106)

Enter a destination field name in the specified statement, and then try the operation again.


Record(s) can't be added; no Insert Data permission on 'name'. (Error 3107)

You must have Insert Data permission for the specified table or query to insert data into it.  To change your permission assignments, see your system administrator or the table or query's creator.


Record(s) can't be edited; no Update Data permission on 'name'. (Error 3108)

You must have Update Data permission for the specified table or query to replace data in it.  To change your permission assignments, see your workgroup administrator or the table or query's creator.


Record(s) can't be deleted; no Delete Data permission on 'name'. (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 or query's creator.


Couldn't read definitions; no Read Definitions permission for table or query 'name'. (Error 3110)

You must have Read Definitions permission for the specified table or query to read its definition.  To change your permission assignments, see your system administrator or the table or query's creator.


Couldn't create; no Create permission for table or query 'name'. (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.


Record(s) can't be read; no Read Data permission on 'name'. (Error 3112)

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


Can't update 'field name'; field not updatable. (Error 3113)

Possible causes:

The specified field is part of a TableDef or dynaset-type Recordset object 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 Tabledef objects, and you tried to update one of the fields in the query's results (the resulting dynaset-type Recordset).


Can't include Memo or OLE object when you select unique values 'statement'. (Error 3114)

Remove the DISTINCT reserved word or the Memo or OLE object field from the statement.


Can't have Memo or OLE object in aggregate argument 'statement'. (Error 3115)

You can't include Memo or OLE object fields in an aggregate function.


Can't have Memo or OLE object in criteria 'criteria' for aggregate function. (Error 3116)

The HAVING clause of an SQL statement can't include Memo or OLE object fields.


Can't sort on Memo or OLE object 'clause'. (Error 3117)

The ORDER BY clause of an SQL statement can't include Memo or OLE object fields.


Can't join on Memo or OLE object 'name'. (Error 3118)

You can't join Memo or OLE object fields.  The field you use to logically tie two or more tables together must be some other data type, such as Character or Integer.


Can't group on Memo or OLE object 'clause'. (Error 3119)

The GROUP BY clause of an SQL statement can't include Memo or OLE object fields.


Can't group on fields selected with '*' 'table name'. (Error 3120)

You tried to execute a SELECT statement that groups or totals all fields in a single table, selected with an asterisk ( * ).  This error occurs, for example, if you enter the following SQL statement:

SELECT Orders.* FROM Orders GROUP BY ShipVia;


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

You tried to execute a SELECT statement that groups or totals all fields from all tables, selected with an asterisk ( * ).

Possible cause:

You created an SQL statement that includes an aggregate function or GROUP BY clause 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 ShipVia;


'Name' 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.


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.


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

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


'Name' 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.


Invalid bracketing of name 'name'. (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.


INSERT INTO statement contains unknown field name 'field name'. (Error 3127)

You tried to use the INSERT INTO statement with the specified field name, but that field doesn't exist in the output table.  Make sure you've typed the name correctly, and then 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.  Instead, you typed field names (for example, Customers.Address instead of Customers.*).


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.


Syntax error in DELETE statement. (Error 3130)

You entered an SQL statement that has an invalid DELETE statement.  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.

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.

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.

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.

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 inner-join, outer-join, or self-join.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in LEVEL clause. (Error 3136)

You entered an SQL statement that has an invalid reserved word clause.

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.

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 with an invalid PARAMETERS declaration.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in PROCEDURE clause. (Error 3140)

You entered an SQL statement that has an invalid PROCEDURE clause.

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.

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.

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.

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.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


ODBC{bmc emdash.bmp}call failed. (Error 3146)
ODBC [image] call failed. (Error 3146)

Using ODBC, 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.  Make sure the network is available, and then try the operation again.


ODBC{bmc emdash.bmp}connection to 'name' failed. (Error 3151)
ODBC [image] connection to 'name' failed. (Error 3151)

Using ODBC, the connection to the specified SQL database or table couldn't be made.  If the SQL database is on a network drive, make sure the network is available, and then try the operation again.


ODBC{bmc emdash.bmp}couldn't find DLL 'name'. (Error 3154)
ODBC [image] couldn't find DLL 'name'. (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.  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.


OODBC{bmc emdash.bmp}insert on attached (linked) table failed. (Error 3155)
ODBC [image] insert on attached (linked) table failed. (Error 3155)

Using ODBC, you tried to insert data into an SQL database; that insertion couldn't be completed.

Possible causes:

The insertion would have caused a rule violation.

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.  Make sure the network is available, and then try the operation again.


ODBC{bmc emdash.bmp}delete on attached (linked) table failed. (Error 3156)
ODBC [image] delete on attached (linked) table failed. (Error 3156)

Using ODBC, you tried to delete data from an SQL database; the deletion couldn't be completed.

Possible causes:

The deletion would have caused a rule violation.

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.  Make sure the network is available, and then try the operation again.


ODBC{bmc emdash.bmp}update on attached (linked) table failed. (Error 3157)
ODBC [image] update on attached (linked) table failed. (Error 3157)

Using ODBC, you tried to update data in an SQL database; that update couldn't be completed.

Possible causes:

The update would have caused a rule violation.

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.  Make sure the network is available, 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 on a database page 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.


Not a valid bookmark. (Error 3159)

You tried to set a bookmark to an invalid string.

This error can occur if you set the Bookmark property to a string that wasn't saved from previously reading a Bookmark property.  For example, the following code produces this error:

Sub MyFunction

Dim dbsBiblio As Database, rstEmployees As Recordset

Dim strPlaceholder As String

Set dbsBiblio = OpenDatabase("biblio.mdb")

Set rstEmployees = dbsBiblio.OpenRecordset("Employees", dbOpenDynaset)

strPlaceholder = "1"

rstEmployees.Bookmark = strPlaceholder	' Not a valid bookmark.

End Sub


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.


Couldn't decrypt file. (Error 3161)

You tried to access an encrypted Btrieve or Paradox table, but the password you provided isn't correct.  Try the operation again by entering the correct password.


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.


Couldn't perform operation; 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.


Field can't be updated. (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 open .INF file. (Error 3165)

You tried to attach (link) a dBASE table, but the associated .INF file that contains index information about that table could not be opened or created.

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.


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.  Make sure the .DBT file is in the same directory as the .DBF file, and then try the operation again.


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.


Invalid .INF file. (Error 3168)

You tried to access a dBASE table, but its associated .INF file is invalid or has become corrupted.  Reattach (relink) the table, making sure you specify the correct indexes.


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 OLE object field in an expression where it isn't 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.


Couldn't find installable ISAM. (Error 3170)

An installable ISAM's DLL file couldn't be found.  This file is required for attaching (linking) external tables (other than ODBC or Microsoft Jet database tables).  The locations for all ISAM drivers are maintained in the Windows Registry.  These entries are created automatically when you install your application.  If you change the location of these drivers, you need to correct your application setup program to reflect this change and make the correct entries in the Registry.

Possible causes:

An entry in the Registry 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 or driver.  Exit the application, correct the registration database, and try the operation again.

One of the entries in the Registry points to a network drive and that network isn't connected.  Make sure the network is available, and then try the operation again.


Couldn't find net path or user name. (Error 3171)

One or more entries in the ISAM Engines\Paradox section of the Registry is invalid.  Correct the invalid entries, and then try the operation again.


Couldn't open PARADOX.NET. (Error 3172)

Possible causes:

The ParadoxNetPath entry in the [Paradox ISAM] section of the Registry 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, and try the operation again.

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


Couldn't open table 'MSysAccounts' in the system database file. (Error 3173)

This operation requires the SYSTEM.MDW file, which contains the security and option settings for Microsoft Jet database tables.

Possible causes:

The SystemDB entry in the Registry points to a network drive that isn't connected.  Make sure the network drive is available, and then try the operation again.

The SYSTEM.MDW file is corrupted.  If you have a backup copy of SYSTEM.MDW, copy it to the location specified in the SystemDB entry in the Registry.


Couldn't open table 'MSysGroups' in the system database file. (Error 3174)

This operation requires the SYSTEM.MDW file, which contains the security and option settings for Microsoft Jet database tables.

Possible causes:

The SystemDB entry in the Registry points to a network drive that isn't connected.  Make sure the network drive is available, and then try the operation again.

The SYSTEM.MDW file is corrupted.  If you have a backup copy of SYSTEM.MDW, copy it to the location specified in the SystemDB entry in the Registry.


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.  Make sure you entered it correctly, and then try the operation again.


Couldn't open file 'name'. (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.


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.


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.


Couldn't write to file 'name'. (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.


Invalid range. (Error 3181)

You attempted to import an invalid range of spreadsheet cells.


Invalid file format. (Error 3182)

Possible causes:

The file you tried to read or attach (link) is corrupted.  Restore a backup copy of the file to your disk, and then try the operation again.

The file format is not recognized.  If the file is a Btrieve, dBASE, or Paradox file, run Setup to install the installable ISAM, and then attach (link) the file.


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.  Your temporary disk location is based on the TEMP DOS environment variable, which was set when your system started.

For example, you may be trying to create a query that creates temporary files larger than the temporary disk.  Reduce the size of the temporary files by accessing 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 fewer records.  Dynaset-type and snapshot-type Recordset objects record keys and data to the temporary disk.

Select a different drive for your temporary disk.

If the temporary disk is a RAM disk, increase the size of the disk or move it to a fixed disk.

Free some space by deleting data or by removing unneeded tables, queries, forms, macros, and modules from your database.

Free some space by compressing deleted records out of your database.

If you still need additional space, consider removing other unused files from your disk.


Couldn't execute query; couldn't find attached, or linked, table. (Error 3184)

Possible causes:

The attached, or linked, table no longer exists or has been renamed or moved.  Reattach the table and then try to execute the query again.

The attached, or linked, table is on a network drive and the network isn't connected.  Make sure the network is available, and then try to execute the query again.


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

The Microsoft Jet database supports up to 255 fields per table, but the other database supports fewer fields.  A SELECT...INTO statement 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.


Couldn't save; currently locked by user 'name' on machine 'name'. (Error 3186)

Possible causes:

You tried to save a record on a 2K database page that is currently locked by another user.  Wait for the other user to finish working with the record, and then try the operation again.


Couldn't read; currently locked by user 'name' on machine 'name'. (Error 3187)

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


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.


Table 'name' is exclusively locked by user 'name' on machine 'name'. (Error 3189)

You can't access the specified table because it is exclusively locked by another user.  Contact the other user, or wait for the other user to release the lock, and then try the operation again.


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.


Can't define field more than once. (Error 3191)

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


Couldn't find output table 'name'. (Error 3192)

You tried to use an INSERT INTO statement with the specified table, which doesn't exist.  Make sure you entered the name correctly, and then try the operation again.


No UserName. (Error 3193)

For security purposes, the operation you attempted requires a valid user name.


No machine name. (Error 3194)

The Microsoft Jet database engine couldn't determine the name assigned to your computer as registered on the network.


Couldn't use 'database name'; database already in use. (Error 3196)

The specified database is currently being used by another user or session.  Wait for the other user or session to finish working with the database, and then try the operation again.


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 when multiple users open a table or create a Recordset and use optimistic locking.  Between the time you used the Edit 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.


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.


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.


Can't delete or change record. Since related records exist in table 'name'', referential integrity rules would be violated. (Err
Can't delete or change record.  Since related records exist in table 'name', 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 add or change record.  Referential integrity rules require a related record in table 'name'. (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.


Couldn't save; currently locked by another user. (Error 3202)

Possible causes:

You tried to save a record on a 2K database page that is currently locked by another user.  Wait for the other user to finish working with the record, and then try the operation again.


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

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

Possible cause:

You used a SELECT statement 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, OrderID, Sum([Sum2]) AS Expr1

FROM Orders

GROUP BY OrderID

PIVOT ShipName;

The 'expression' parameter of the alert would contain the expression Sum([Sum2]) from the SELECT clause, because this references an alias used in the same SELECT statement and acts as a subquery against Sum([Sum1]).


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.


Too many crosstab column headers 'value'. (Error 3205)

You executed an SQL statement that tried to create too many columns.  The specified value is the column that produced this error.

You can reduce the number of columns by adding additional conditions to the WHERE clause or, if there is no WHERE clause, add one.


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.


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.


Invalid Deleted entry in XBASE section of initialization setting. (Error 3208)

To complete this operation:

1.	Exit your application.

2.	Correct the Deleted entry in the [dBASE ISAM] section of the Registry.

3.	Restart your application, and then try the operation again.


Invalid Stats entry in XBASE section of initialization setting. (Error 3209)

To complete this operation:

1.	Exit your application.

2.	Correct the Stats entry in the [dBASE ISAM] section of the Registry.

3.	Restart your application, and then try the operation again.


Connection string too long. (Error 3210)

The connection string in the IN clause of an SQL statement can't be longer than 255 characters.  Correct your entry, and then try the operation again.  (You may want to use the ODBC Connection String Builder.)


Couldn't lock table 'name'; 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 lock table 'name'; currently in use by user 'name' on machine 'name'. (Error 3212)

The table can't be locked because it is currently in use.  Wait for the other user's transaction to complete, and then try the operation again.


Invalid Date entry in XBASE section of initialization setting. (Error 3213)

To complete this operation

1.	Exit your application.

2.	Correct the Date entry in the [dBASE ISAM] section of the Registry.

3.	Restart your application, and then try the operation again.


Invalid Mark entry in XBASE section of initialization setting. (Error 3214)

To complete this operation

1.	Exit your application.

2.	Correct the Mark entry in the [dBASE ISAM] section of the Registry.

3.	Restart your application, and then try the operation again.


Too many Btrieve tasks. (Error 3215)

Too many applications are using 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.


Parameter 'name' 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 expects a table name.

Change the parameter type from Text to TableID, and then try the operation again.


Parameter 'name' 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 CustomerID

FROM Customers IN Param1;

Param1 is a text parameter, but the FROM clause requires a database parameter.

Change the parameter type from Text to Database, and then try the operation again.


Couldn't update; currently locked. (Error 3218)

You tried to update data that is located on a page that is currently locked.

Possible causes:

You tried to save a query that is being used by someone else.  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 data page containing a record that is already open or locked.


Invalid operation. (Error 3219)

Possible causes:

You tried to write to a read-only property.  See the Help topic for the property to determine whether it is read/write.

You tried to use a method or property on a type of Recordset object that the method or property doesn't apply to.  See the Recordset Object, Recordsets Collection topic to determine which methods and properties apply to a given type of Recordset object.

You tried to append a property to a Properties collection of an object that doesn't support user-defined properties.


Incorrect collating sequence. (Error 3220)

You tried to attach (link) a Paradox table that was created with an international sort order that isn't the same as the one you are using.


Invalid entries in Btrieve section of initialization setting. (Error 3221)

An entry in the [Btrieve] section of the Registry 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, and then restart the application to try the operation again.


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.


'Parameter name' isn't a valid parameter name. (Error 3223)

The parameter name is longer than 64 characters or contains invalid characters.  Correct the name, and then try the operation again.


Can't read Btrieve data dictionary. (Error 3224)

Restore a backup copy of the DDF file, and then try the operation 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.


Invalid Century entry in [dBASE ISAM] section of initialization setting. (Error 3227)
Invalid Century entry in XBASE section of initialization setting. (Error 3227)

To complete this operation:

1.	Exit your application.

2.	Correct the Century entry in the [dBASE ISAM] section of the Registry entry.

3.	Restart your application, and then try the operation again.


Invalid collating sequence. (Error 3228)

You have an incorrect value for the Collating Sequence entry in [Paradox ISAM] section of the Registry.

To complete this operation:

1.	Exit the application.

2.	Change the CollatingSequence entry in the [Paradox ISAM] section of the Registry to either ASCII or International.

3.	Restart the application, and then try the operation again.


Btrieve{bmc emdash.bmp}can't change field. (Error 3229)
Btrieve [image] can't change field. (Error 3229)

You tried to update a field in a Btrieve table that is part of an index that can't be modified.  Use Novell Xtrieve or another program to change the attribute of the index that can't be modified, 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.


ODBC{bmc emdash.bmp}field would be too long; data truncated. (Error 3231)
ODBC [image] field would be too long; data truncated. (Error 3231)

You tried to perform an ODBC operation that would have resulted in a field that is too long.  The data has been truncated to the maximum allowable length.


ODBC{bmc emdash.bmp}couldn't create table. (Error 3232)
ODBC [image] 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{bmc emdash.bmp}remote query timeout expired. (Error 3234)
ODBC [image] remote query timeout expired. (Error 3234)

The ODBC 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.


ODBC{bmc emdash.bmp}data type not supported on server. (Error 3235)
ODBC [image] data type not supported on server. (Error 3235)

The ODBC server doesn't support the same SQL data types as the database engine or your application.  The data has not been placed on the server.


ODBC{bmc emdash.bmp}data out of range. (Error 3238)
ODBC [image] data out of range. (Error 3238)

Using ODBC, you tried to read from or write to an SQL database, and the data isn't within the prescribed limits.


Too many active users. (Error 3239)

In a multiuser environment, Microsoft Jet 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{bmc emdash.bmp}missing Btrieve engine. (Error 3240)
Btrieve [image] missing Btrieve engine. (Error 3240)

You tried to perform an operation that requires the specified file.  To use data access to read and write data to a Btrieve file, you must have a copy of the stand-alone Btrieve for Windows engine.  This file must be in your \WINDOWS\SYSTEM directory.

If you don't have a copy of this file, you can purchase Btrieve for Windows by contacting your local software dealer.


Btrieve{bmc emdash.bmp}out of resources. (Error 3241)
Btrieve [image] out of resources. (Error 3241)

While working with a Btrieve file, your application ran out of resources.  Exit your application and increase one or more settings in the [Btrieve] section of the Registry.  Then restart your application and try the operation again.

For more information, refer to your Btrieve documentation.


Invalid reference in SELECT statement. (Error 3242)

You entered an invalid field or table reference in the SELECT statement.  For example, the reference may be misspelled or doesn't exist.


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.


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.


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 can't be parsed:

"Name", Date, "ID " Number, Phone" Number"

The first two fields are valid, but the third and fourth aren't because they contain nonspace characters outside of the quotation marks.

Check the import table for properly matched quotation marks, and then try the import 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 statement, or an internal transaction created by the Microsoft Jet database engine, as when you delete multiple records in a single operation.


ODBC{bmc emdash.bmp}attached, or linked, table definition has changed. (Error 3247)
ODBC [image] attached, or linked, table definition has changed. (Error 3247)

The definition or structure of an attached (linked) table changed since you created the link.  Delete the link, and then reattach the table.


Invalid NetworkAccess entry in initialization setting. (Error 3248)

To complete this operation:

1.	Exit the application.

2.	Correct the NetworkAccess entry in the Registry.  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 initialization setting. (Error 3249)

To complete this operation:

1.	Exit the application.

2.	Using Microsoft Windows Notepad or another text editor, correct the NetworkAccess entry in the Registry.  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.


Couldn't build key. (Error 3250)

When building a primary index, the Microsoft Jet database engine couldn't build a primary key.  Make sure the key fields are named properly and that there are no duplicate records based on this key.

This error can occur when you use the Seek method and pass it a value for a field that is not part of the index.  For example, suppose you want to use the Seek method on a Recordset whose current index uses the LastName field of the underlying table, and you write it this way:

rstEmployees.Seek "=", "Smith", "Joe"

Jet will try to construct a primary key from two columns, but because one column is indexed, the attempt will fail and this error results.


Operation is not supported for this type of object. (Error 3251)

You were attempting to execute a method or assign a value to a property that is generically valid for the object, but isn't supported in this specific instance.  For example, the Edit method is generally valid for Recordset objects, but not for a snapshot-type Recordset.  This error could also occur in cases where the operation isn't permitted due to the type or status of the object [image] as when trying to use the MovePrevious method on a forward-only scrolling snapshot-type Recordset.


Can't open form whose underlying query contains a user-defined function that attempts to set or get the form's Recordset Clone p
Can't open form whose underlying query contains a user-defined function that attempts to set or get the form's Recordset Clone property. (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.


ODBC{bmc emdash.bmp}Can't lock all records. (Error 3254)
ODBC [image] Can't lock all records. (Error 3254)

Using ODBC, you tried to lock all of the records in an SQL database.


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 (relink) the table, or use Microsoft Windows Notepad or another text editor to update the .INF file.


Syntax error in WITH OWNERACCESS OPTION declaration. (Error 3257)

Possible causes:

The WITH OWNERACCESS OPTION declaration 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, if present:

SELECT * FROM [My Table] WITH OWNERACCESS OPTION;


Query contains ambiguous outer joins. (Error 3258)

You tried to execute an SQL statement that contains multiple joins; 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.CustomerID = Orders.CustomerID,

Orders INNER JOIN [Order Details]

ON Orders.OrderID = [Order Details].OrderID;

Executing 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 is performed before the LEFT JOIN and RIGHT JOIN operation:

Query1

SELECT * FROM Orders, [Order Details],

Orders INNER JOIN [Order Details]

ON Orders. OrderID = [Order Details].OrderID;

Query2

SELECT * FROM Customers, Query1,

Customers LEFT JOIN Query1

ON Customers.CustomerID = Orders.CustomerID;


Invalid field data type. (Error 3259)

The data type specified in the Field object Type property isn't valid.  Choose one of the valid types as shown in the Type property Help topic.


Couldn't update; currently locked by user 'name' on machine 'name'. (Error 3260)

You tried to update data that is located on a page that is currently locked.

Possible causes:

You tried to save a query being used by someone else.  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 data page containing a record that is already open or locked.


Table 'name' is exlusively locked by user 'name' on machine 'name'. (Error 3261)
Table 'name' is exclusively locked by user 'name' on machine 'name'. (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.


Couldn't lock table 'name'; currently in use by user 'name' on machine 'name'. (Error 3262)

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


Invalid database object. (Error 3263)

The Database object specified isn't the result of the OpenDatabase method, or it has been modified and is no longer valid.


No field defined - cannot append Tabledef or Index. (Error 3264)

You can't append a Tabledef until you define one or more fields.  Use the CreateField method to create fields, append them to your TableDef object, and then append the TableDef object to the TableDefs collection.


'Name' not found in this collection. (Error 3265)

An attempt to reference a name in a collection failed.

Possible causes:

The object doesn't exist in this collection.  Make sure the object is appended to a collection before referencing it.

There is more than one object with this name in the collection; using its name is an ambiguous reference.  Reference the object by its ordinal position in the collection (for example, Recordsets(3)).


Can't append. Field is part of a Fields collection. (Error 3266).

A Field object was specified as an argument to an Append operation when it already is a member of an existing Fields collection.  Use the Dim statement and CreateField method to declare a new Field object and specify its values, and retry the operation with the new Field object.


Property can be set only when the field is part of a Recordset object's Fields collection. (Error 3267)

This property is valid only for Field objects that are part of a Recordset object's Fields collection.  See the Fields collection Summary topic for a list of properties available for different Fields collections.


Can't set this property once the object is part of a collection. (Error 3268)

An attempt was made to change the value of a property of an object (TableDef, Field, and so on) that is already appended to a collection.


Can't append. Index is part of an Indexes collection. (Error 3269)

An Index object was specified as an argument to an Append operation when it already is a member of an existing Indexes collection.  Use the Dim statement and CreateIndex method to declare a new Index object and specify its values, and then retry the operation with the new Index object.


Property not found. (Error 3270)

The specified property couldn't be found.

Possible causes:

The property doesn't exist.  Check the spelling of the property in your code.

If the property is user-defined, it may have been deleted from the collection.


Invalid property value. (Error 3271)

Possible causes:

The setting for the Value property of the Parameter object is too long or is otherwise incorrect.

The Index object name is a zero-length string [" "].  You must enter a name for the Index object when appending the object to the Indexes collection.

The Workspace object name is a zero-length string.  You must enter a name for the Workspace object when appending the object to a Workspaces collection.


Object isn't a collection. (Error 3272)

You've referred to an object as though it were a collection.  For example, a statement such as MyQuery.Refresh or MyQuery(2) causes this error.


Method not applicable for this object. (Error 3273)

You tried to use a method on an object that doesn't support that method.  Refer to the Summary topic for the object to see a list of valid methods for that object.


External table isn't in the expected format. (Error 3274)

The format of the table has changed since it was attached (or linked).  Attach (or relink) the table again, and then retry the operation.


Unexpected error from external database driver 'error number'. (Error 3275)

The external database driver (as specified) returned an error.  This error can be caused by performing an operation not supported on this type of external database.


Invalid database ID. (Error 3276)

The Database object specified isn't the result of the OpenDatabase method, or it has been modified and is no longer valid.


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.


Database engine has not been initialized. (Error 3278)

The database engine cannot be initialized.

Possible causes:

There is a conflict with another application that uses the Microsoft Jet database engine.  Quit all other applications, and then restart your application.

An error occurred during installation and setup.  Reinstall your application.


Database engine has already been initialized. (Error 3279)

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


Can't delete a field that is part of an index or is needed by the system. (Error 3280)

To delete a field that is part of an index, you must first delete the index.


Can't delete this index.  It is either the current index or is used in a relationship. (Error 3281)

If the index is used in a relationship, you must delete the relationship before you can delete the index.  If the index is specified as the current index by the Index property, you must set the property to a different index before you can delete the index.


Can't create field or index in a table that is already defined. (Error 3282)

You can't add a field or create an index on an attached (or linked) table that contains data.  Once a table is populated with data, you can't change the table design or indexes.  Create a new table with the altered design and transfer the data to it using an action query.


Primary key already exists. (Error 3283)

You're attempting to define a second primary key for this table.  Each table can have only one primary key.  Remove the reference to the second primary key.


Index already exists. (Error 3284)

You can't have two indexes with the same name in a table.  Rename one of the indexes.


Invalid index definition. (Error 3285)

Possible causes:

You're using the same column twice in an index or relationship, which the Microsoft Jet database engine doesn't permit.

You're creating a relationship using columns with data types that don't match.  In Microsoft Jet databases, you can only relate columns with identical data types or a Counter column with a Number column set to a Long Integer.


Format of memo file doesn't match specified external database format. (Error 3286)

Your application can't read the memo file associated with the database you're trying to import or attach (link) and consequently can't import or attach (link) the file.  The memo file may be in the wrong format; for example, if you selected dBASE IV as the data source and the memo file is in a FoxPro format.


Can't create index on the given field. (Error 3287)

You're trying to create an index on a Memo or OLE Object field.  Specify another field, and then try the operation again.

This can also occur if you try to create an index on a Btrieve table on a 1-byte field.


Paradox index is not primary. (Error 3288)

You are attempting to create an index on a Paradox table for which no other indexes are defined.  The first index created on a Paradox table must be a primary index.

Possible solutions:

Redefine the index as the primary index.

If the index you're attempting to create isn't the primary index, create the primary index first.


Syntax error In CONSTRAINT clause. (Error 3289)

You entered an SQL statement that includes an invalid CONSTRAINT clause.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in CREATE TABLE statement. (Error 3290)

You entered an SQL statement that includes an invalid CREATE TABLE statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in CREATE INDEX statement. (Error 3291)

You entered an SQL statement that includes an invalid CREATE INDEX statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in field definition. (Error 3292)

A syntax error occurred in the field definition of a CREATE TABLE or ALTER TABLE statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in ALTER TABLE statement. (Error 3293)

You entered an SQL statement that includes an invalid ALTER TABLE statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in DROP INDEX statement. (Error 3294)

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.


Syntax error in DROP TABLE or DROP INDEX. (Error 3295)

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.


Join expression not supported. (Error 3296)

Possible causes:

Your SQL statement contains multiple joins in which the results of the query can differ, depending on the order in which the joins are performed.  You may want to create a separate query to perform the first join, and then include that query in your SQL statement.

The ON statement in your JOIN operation is incomplete or contains too many tables.  You may want to put your ON expression in a WHERE clause.


Couldn't import table or query.  No records found, or all records contain errors. (Error 3297)

Microsoft Jet couldn't find the table or query you tried to import.  Check the path you specified and try it again.


There are several tables with that name.  Please specify owner in the format 'owner.table'. (Error 3298)

More than one table with that name exists in the remote ODBC database.  To resolve the ambiguity, specify the owner of the table you want to access, using the owner.table syntax.


ODBC Specification Conformance Error 'message'.  This error should be reported to the ODBC driver vendor. (Error 3299)

This error can be caused by any of a number of problems with your ODBC driver.  Write down the error number indicated in the message and report it to your driver vendor.


Can't create a relationship. (Error 3300)

You are attempting to create a relationship that isn't allowed.  For example, the tables may be in different databases.


Can't perform this operation; features in this version are not available in databases with older formats. (Error 3301)

The database was stored in an earlier version of the Microsoft Jet database engine that doesn't support this feature.  Either the database needs to be converted to Microsoft Jet version 2.0 or 3.0 format, or this particular operation needs to be revised to avoid using the unsupported feature.


Can't change a rule while the rules for this table are in use. (Error 3302)

A record in this table has been changed by another user, or has been changed by you in a separate session of your application, and is currently locked.  You can't modify the rules in a table while a record in that table is locked.

If you have locked the record in a separate session, save the record, and then make your changes.  If another user has locked the record, wait a little while, and then save your rule modifications.


Can't delete this field.  It's part of one or more relationships. (Error 3303)

You're trying to delete a field for which relationships have been defined in the database.  To delete the field, you must first delete its relationships.


You must enter a personal identifier (PID) consisting of at least four and no more than 20 characters and digits. (Error 3304)

A personal identifier (PID) must be at least 4 characters and no more than 20 characters long.


Invalid connection string in pass-through query. (Error 3305)

The connection string for a pass-through query doesn't begin with "ODBC;".


At most one field can be returned from a subquery that doesn't use the EXISTS keyword. (Error 3306)

You've written a subquery that can return more than one field without using the EXISTS reserved word in the main query's FROM clause.  Revise the SELECT statement of the subquery to request only one field.


The number of columns in the two selected tables or queries of a union query don't match. (Error 3307)

The two tables or queries joined by the UNION operation must generate the same number of columns.  Remove columns from the SELECT statement that has too many columns or include more columns in the SELECT statement that has too few.

Tip   You can include constants instead of columns in the SELECT statement that has too few columns.  For example, the following union query generates three columns from the first SELECT statement but one column and two constants in the second SELECT statement.  The query returns all countries in the Employees and Regions tables.  From the Employees table, the query also returns the first and last name of an employee.  If the country value is from the Regions table, however, the query returns Null in the First Name and Last Name columns.

SELECT Country, FirstName, LastName FROM Employees

UNION SELECT Country, NULL, NULL FROM Regions;


Invalid TOP argument in select query. (Error 3308)

An invalid parameter appeared in the TOP clause of a SELECT statement.  The value placed after the TOP reserved word must be a positive integer.  If the PERCENT reserved word is also used, the integer can't be greater than 100.


Property setting can't be larger than 2 KB. (Error 3309)

You are trying to set a property value of an object to a size greater than the largest permissible size of 2 kilobytes.  Shorten the length of the property value.


This property isn't supported for external data sources or for databases created in a previous version. (Error 3310)

You attempted to set or check a property that isn't available for this object in a database stored in a Microsoft Jet database version 1.x, 2.x, or in an external data source.  Search for the object in Help, and then display the Summary topic for the object to see a list of its valid properties.


Property specified already exists. (Error 3311)

You tried to append a new Property object to a collection that contains a property of the same name.  Check to see whether you've misspelled the new Property object's Name property, or refer to the Help topic for the existing property of the same name to see whether you need to create a new Property object.


Validation rules and default values can't be placed on system or attached (linked) tables. (Error 3312)

You're trying to set the DefaultValue, ValidationRule, ValidationText, or Required property on a table, field, or other object that is prohibited by your application.  For example, you're setting a property on a system object.


Can't place this validation expression on this field. (Error 3313)

You're trying to set validation properties on a field (such as a Counter or OLE field) that doesn't allow this type of property.  Use a different field to validate data or, if you have not added data to the table, redefine the data type for the field.


Field 'name' can't contain a null value. (Error 3314)

The Required property for this field is set to Yes, prohibiting the entry of a Null in the field.  Enter a value in the field.


Field 'name' can't be a zero-length string. (Error 3315)

The AllowZeroLength property for this field is set to No, prohibiting the entry of a zero-length string in the field.  Enter a different value in the field.


'Table-level validation text'. (Error 3316)

A table-level validation rule was violated.


One or more values entered is prohibited by the validation rule 'rule' set for 'name'. (Error 3317)

The ValidationRule property for this field contains an expression that limits the values that can be entered in the field.  You must enter a value that isn't prohibited by the expression.


Top not allowed in delete queries. (Error 3318)

Top values; that is, those specified in a TOP clause of a SELECT statement, aren't allowed in delete queries.


Syntax error in union query. (Error 3319)

There is a syntax error in an SQL string of the union query.

Possible causes:

A reserved word or argument name is misspelled.

A reserved word or argument is missing.

Punctuation is incorrect.


'Error' in table-level validation expression. (Error 3320)

An error occurred in a table-level validation rule expression or its default value expression.  This could be a syntax error or some other kind of error.


No database specified in connection string or IN clause. (Error 3321)

The Microsoft Jet database engine is unable to connect to an external ISAM database because you haven't specified the name of the database to connect to.  When connecting to an external source of data, you must specify a database name.

Possible causes:

The connection string in the FROM clause of the SELECT statement is missing the parameter, DATABASE=.

The IN clause of the SELECT statement includes a database type argument (indicating to select the data from an external database) but it's missing a database name argument.


Crosstab query contains one or more invalid fixed column headings. (Error 3322)

The list of entries for a fixed column heading of a crosstab query (the PIVOT clause in a TRANSFORM statement) isn't valid.

Possible causes:

No entries in the list.  There must be at least one value in the parentheses following the IN reserved word in the PIVOT clause.

A blank entry appears in the list.  Two commas in a row (,,) create a blank entry.

The list contains a field name of more than 64 characters.

Correct the PIVOT clause and execute the query again.


The query cannot be used as a row source. (Error 3323)

Possible causes:

The query being used as a row (record) source is an action query or a data-definition query.

In version 1.x code, the ListFields method was used on an action query or data-definition query.


The query is a DDL query and cannot be used as a row source. (Error 3324)

You tried to run an action query or data-definition query without using the Execute method.


Pass-through query with ReturnsRecords property set to True did not return any records. (Error 3325)

A pass-through query didn't return any records even though the ReturnsRecords property is set to Yes (True).  If a pass-through query doesn't return records, set the ReturnsRecords property to No (False).


This Recordset is not updatable. (Error 3326)

You attempted to edit data in a field that is bound to a snapshot-type Recordset object.  Snapshot fields can't be edited.


Can be present only in version 1.0 format. (Error 3334)

You are attempting to use a feature that is no longer supported in the current version of the application.  To learn about the current approach to completing your task, see Examples of Converting Code to Jet Version 2.5.


Btrieve: Invalid IndexDDF option in initialization setting. (Error 3336)

The setting for the IndexDDF entry in the [Btrieve ISAM] section of the initialization file or Registry isn't valid.  The IndexDDF entry determines the manner in which the Btrieve external ISAM database is to handle the INDEX.DDF file, which is updated whenever indexes are created or deleted.

Valid settings are:

Require [image] INDEX.DDF file is required in the database directory, in addition to FILE.DDF and FIELD.DDF.

Maintain [image] Updates the INDEX.DDF file if it exists, but doesn't generate an error if it doesn't.

Ignore [image] Makes no attempt to update the INDEX.DDF file, regardless of whether or not it exists.


Invalid DataCodePage option in initialization setting. (Error 3337)

The DataCodePage setting for the external data source you are attempting to use isn't valid.  This setting is in the corresponding ['external data source' ISAM] section (for example, [Btrieve ISAM]) in the Registry.

Valid settings are:

OEM [image] Data is stored as OEM data; OemToAnsi and AnsiToOem conversions are done.

ANSI [image] Data is stored as ANSI data; OemToAnsi and AnsiToOem conversions aren't done.


Btrieve: Xtrieve options aren't correct in initialization setting. (Error 3338)

One or more of the XTRPATH, XTRENV, and XTRPINDEX entries in the Registry is invalid.

Possible causes and solutions:

XTRPATH is the directory search path for locating data files.  The format for this entry is:

XTRPATH=dir1;dir2;dir3

where dir1, dir2, and dir3 are full directory paths (for example, XTRPATH=C:\DATA;D:\FILES;E:\DATA).

XTRENV is the directory and filename for the Xtrieve environment file (for example, XTRENV=C:\XTRV\XTRIEVE.ENV).

XTRPINDX is a pointer to the directory in which to create new Xtrieve tables, expressed as a numeric value corresponding to a directory in XTRPATH, with the first directory having an XTRPINDX of 1, the second having an XTRPINDX of 2, and so on.  In the XTRPATH shown previously , an XTRPINDX value of 2 indicates the creation of new Xtrieve tables in the directory D:\FILES.


Btrieve: Invalid IndexDeleteRenumber option in initialization setting. (Error 3339)

The setting for the IndexDeleteRenumber entry in the [Btrieve ISAM] section of the initialization file or Registry isn't valid.  The IndexDeleteRenumber entry determines whether remaining indexes are renumbered if one is deleted.

Valid settings are:

On [image] Renumbers.

Off [image] Doesn't renumber.

On is consistent with Btrieve version 5.1x behavior.  Off is consistent with Btrieve version 6.0 behavior.


Query 'name' is corrupt. (Error 3340)

You've referenced an undefined query name.  Check the queries listed in the QueryDefs collection to make sure you referenced a valid query name.


Current field must match join key 'name' on 'one' side of outer join. (Error 3341)

You've tried to enter a value into the join field in the many-only table of an outer join with no corresponding value in the join field of the "one" side table.  First enter a record in the "one" side table with the desired key value.  Then make the entry with the desired join field in the "many-only" table.


Invalid Memo or OLE object in subquery 'name'. (Error 3342)

A subquery can't return a Memo or OLE object, and it can't be compared to a Memo or OLE object in an expression.


Unknown or invalid reference 'name' in validation expression or default value in table 'name'. (Error 3344)

Your expression refers to a field incorrectly, or to a field that doesn't exist.  Check to make sure the field name is valid and spelled correctly.


Unknown or invalid field reference 'name'. (Error 3345)

Your expression refers to a field incorrectly or to a field that doesn't exist.  Check to make sure the field name is correct.


Number of query values and destination fields aren't the same. (Error 3346)

The INSERT INTO (Append) query either doesn't have enough destination fields or it has more fields in the VALUES or SELECT list than there are fields in the destination table.  Select a matching number of fields.


Numeric field overflow. (Error 3349)

The data in a Btrieve field is too large to represent in your application.


Object is invalid for operation. (Error 3350)

You used the RefreshLink method on an object other than an attached (linked) table.  An object ceases to exist when it is destroyed and when its associated data object is closed or is no longer defined in the current scope.


ORDER BY expression 'expression' uses non-output fields. (Error 3351)

In a union query, you've included nonoutput fields in an ORDER BY expression.  Only those fields requested in the first query can be included in an ORDER BY expression.


No destination field name in INSERT INTO statement 'statement'. (Error 3352)

The destination field name or names can't be determined from the expression in the SELECT clause of the INSERT INTO statement.


Btrieve: Can't find file FIELD.DDF. (Error 3353)

The Btrieve driver can't find the FIELD.DDF file pointed to by the FILE.DDF file.

Possible solutions:

If the FIELD.DDF file exists, fix the reference to it in the FILE.DDF file using either Novell Xtrieve or another .DDF file builder.

If the FIELD.DDF file doesn't exist, create it using either Novell Xtrieve or another .DDF file builder.


At most one record can be returned by this subquery. (Error 3354)

A subquery of this kind can't return more than one record.  Revise the SELECT statement of the subquery to request only one record.


Syntax error in default value. (Error 3355)

Possible causes:

An unknown function name was included in the default value expression in a table-level validation rule.

A default value expression in a table-level validation rule is syntactically incorrect.


The database is opened by user 'name' on machine 'name'. (Error 3356)

Possible causes:

You attempted to open a database that is already opened exclusively by user 'name'.  You cannot open the database until the other user closes it.

You attempted to open exclusively a database that is already open in shared (non-exclusive) mode by user 'name'.  You can open the database only in shared mode until the other user closes it.


Can't open Microsoft Jet engine system database. (Error 3358)

You attempted to perform a security-related task, but the system database (typically SYSTEM.MDW) required for the task can't be found.


Pass-through query must contain at least one character. (Error 3359)

The SQL string of a pass-through query must contain at least one character.


Query is too complex. (Error 3360)

The query is too complex.  Reduce the number of fields in the SELECT clause.


Unions not allowed in a subquery. (Error 3361)

You can't use a UNION operation in a subquery expression.  To use a union query in a subquery, first create the union query and save it as a named query.  Then include the name of the saved query in your subquery expression.


Single-row update/delete affected more than one row of an attached (linked) table.  Unique index contains duplicate values. (Err
Single-row update/delete affected more than one row of an attached (linked) table.  Unique index contains duplicate values. (Error 3362)

Your update or delete query affected more than one record in the attached SQL table.  Update and delete can affect only one record at a time.


Can't use Memo or OLE object field 'name' in SELECT clause of a union query. (Error 3364)

A field you specified in the SELECT part of a UNION query in the SQL statement for the query has a field data type of Memo or OLE object.  You can't specify a field of either of these types.


Can't set this property for remote objects. (Error 3365)

This property isn't available for objects associated with ODBC databases.


Can't append a relation with no fields defined. (Error 3366)

You are trying to append a Relation object without any fields to a Relations collection.

To correctly append a Relation

1.	Use the CreateRelation method to create the Relation object.

2.	Set the Table, ForeignTable, and Attributes properties of the Relation object, if you didn't specify them as arguments to the CreateRelation method.

3.	Use the CreateField method to create a new Field object for each field in the primary and foreign keys of the relationship.

4.	Set the Name (if you didn't specify it as an argument to the CreateField method) and ForeignName properties of the Field object or objects to the corresponding Name property settings of the primary key and the foreign key Field objects of each field in the relationship.

5.	Use the Append method to save the Field object or objects in the Fields collection of the Relation object.

6.	Use the Append method to save the Relation object in the Relations collection of the database.


Can't append.  Object already in collection. (Error 3367)

You tried to append an object to a collection that already contains an object of the same name.  Use the Refresh method on the collection and check to see whether the object you want to append already exists, or try changing the object's Name property setting.


Relationship must be on the same number of fields with the same data types. (Error 3368)

The CONSTRAINT clause you're using to create a relationship includes a different number of fields for each table or includes fields with different data types.  Check the number of fields in the CONSTRAINT clause, check the data types of fields to make sure they match, and try again.


Can't modify the design of table 'name'.  It's in a read-only database. (Error 3370)

You can't modify tables in a read-only database.


Can't find table or constraint. (Error 3371)

The table or relationship you specified doesn't exist.  Specify a valid table or constraint name.


No such index 'name' on table 'name'. (Error 3372)

The specified index doesn't exist in the specified table.  Check your code for a misspelling or other error.


Can't create relationship. Referenced table 'name' doesn't have a primary key. (Error 3373)

The table you've referenced in the CONSTRAINT clause doesn't have a primary key.  To create the relationship, you must either create a primary key in the referenced table, or specifically reference one or more uniquely indexed fields to use in the relationship.


The specified fields are not uniquely indexed in table 'name'. (Error 3374)

The specified fields in the referenced table of a CONSTRAINT clause aren't uniquely indexed.


Table 'name' already has an index named 'name'. (Error 3375)

You're trying to create an index that already exists.


Table 'name' doesn't exist. (Error 3376)

The table you specified doesn't exist.  Check the name you specified.


No such relationship 'name' on table 'name'. (Error 3377)

The relationship you specified doesn't exist in this database.  Check the name you specified.


There is already a relationship named 'name' in the current database. (Error 3378)

You must specify a unique name for each relationship you add to a database using data-definition queries.


Can't create relationships to enforce referential integrity. Existing data in table 'name' violates referential integrity rules
Can't create relationships to enforce referential integrity.  Existing data in table 'name' violates referential integrity rules in table 'name'. (Error 3379)

You're trying to create a relationship using the CONSTRAINT clause of the ALTER TABLE statement, but existing data in the two tables violates referential integrity constraints.  For example, there might be records relating to an employee in the related table but no corresponding record for the employee in the primary table.

To create the relationship, you must edit the data so that primary records exist for all related records.


Field 'name' already exists in table 'name'. (Error 3380)

You have entered the same field name twice.  Rewrite your code, giving each field a unique name.


There is no field named 'name' in table 'name'. (Error 3381)

The specified table doesn't contain the specified field.  Check the spelling of the field name.


Size of a field 'name' is too long. (Error 3382)

Text fields in Microsoft FoxPro tables can be no more than 254 characters, and in Microsoft Jet tables, 255.  Redefine the size of the field.


Can't delete field 'name'.  It's part of one or more relationships. (Error 3383)

You're trying to delete a field for which relationships have been defined in the database.  To delete the field, you must first delete its relationships.


Can't delete a built-in property. (Error 3384)

You are trying to delete a Property object defined by the Microsoft Jet database engine.

You can delete only user-defined (including application-defined) properties for which you have Modify Design permission or ones for which Modify Design permission isn't required.


User-defined properties don't support a Null value. (Error 3385)

User-defined Property objects can't be set to Null.  Instead, use the Delete method on the property to remove it from its collection.


Property 'name' must be set before using this method. (Error 3386)

You attempted to append a new Property object to a collection without first setting all of the new object's properties: Value, Type, and Name.


Unknown function 'name' in validation expression or default value on 'name'. (Error 3388)

The function you are referencing is either unknown (because the name is invalid or misspelled) or is a type of function not allowed by the ValidationRule or DefaultValue property.  Among the types of functions not allowed are user-defined, SQL aggregated, and domain aggregate functions.


Query support unavailable. (Error 3389)

You attempted to establish referential integrity on a Relation object of a QueryDef object, which isn't supported.

Change the Attributes property setting of the Relation object to dbRelationDontEnforce.


Account name already exists. (Error 3390)

This is a security problem.  You tried to establish a user account using a name that already exists.  Try again using a different user name.


Can't perform join, group, or sort.  Combined fields are too long. (Error 3393)

The maximum combined length of fields used to join, group, or sort is 255 bytes.  Reduce the number of fields in your join, group, or sort, or use shorter data types and field sizes for the fields.


Can't save property; property is a schema property. (Error 3394)

You tried to set or change a schema property.  When you create a new schema property, specify True as the fourth argument to the CreateProperty method in order to set or delete this property.


Can't perform cascading operation. Since related records exist in table 'name', referential integrity rules would be violated. (
Can't perform cascading operation.  Since related records exist in table 'name', referential integrity rules would be violated. (Error 3396)

The cascade operation you are attempting violates referential integrity rules with the indicated table.  Check the values you are attempting to update or delete, and fix them so they comply with the referential integrity rules.


Can't perform cascading operation.  There must be a related record in table 'name'. (Error 3397)

The cascade operation you are attempting violates a referential integrity rule that requires a related record in the indicated table.  Check the values you are attempting to update or delete and fix them so they comply with the referential integrity rule.


Can't perform cascading operation.  It would result in a null key in table 'name'. (Error 3398)

The cascade operation you are attempting would result in a Null value in a primary key field in the indicated table, which has been set up not to allow null values.  Check the values you are attempting to update and fix them so they don't result in null values.


Can't perform cascading operation.  It would result in a duplicate key in table 'name'. (Error 3399)

The cascade operation you are attempting would result in a duplicate key in the indicated table, which is set up not to allow duplicate primary keys.  Check the values you are attempting to update and fix them so they don't result in duplicate keys.


Can't perform cascading operation.  It would result in two updates to field 'name' in table 'name'. (Error 3400)

The cascade operation you are attempting can't be completed because it would result in two separate updates to the indicated field.  Check the values you are attempting to update, and fix them so that either:

The field is updated only one time.

If the field is updated more than once; the result of each update to the field is the same.


Can't perform cascading operation.  It would cause field 'name' to become null, which is not allowed. (Error 3401)

The cascade operation you are attempting would result in a Null value in the indicated field, which has been set up not to allow null values.  Check the values you are attempting to update and fix them so they don't result in null values in this field.


Can't perform cascading operation.  It would cause field 'name' to become a zero-length string, which is not allowed. (Error 340
Can't perform cascading operation.  It would cause field 'name' to become a zero-length string, which is not allowed. (Error 3402)

The cascade operation you are attempting would result in a zero-length string in the indicated field, which is set up not to allow zero-length strings.  Check the values you are attempting to update and fix them so they don't result in zero-length strings in this field.


Can't perform cascading operation: 'validation text'. (Error 3403)

The cascade operation you are attempting would result in invalid data.  Check the values you are attempting to update and fix them so they comply with the validation rules.


Can't perform cascading operation.  The value entered is prohibited by the validation rule 'rule' set for 'name'. (Error 3404)

The cascade operation you are attempting would result in an invalid value in the indicated field, as established by the field's validation rule.  Check the values you are attempting to update and fix them so they comply with the validation rule.


Error 'error text' in validation rule. (Error 3405)

The expression cannot be evaluated correctly for the reason given in the alert.  For example, if the error text is Type Mismatch, the property setting doesn't match the data type defined for the field.


Error 'error text' in default value. (Error 3406)

The expression you're trying to set the DefaultValue property to is invalid.  Set the property to a valid expression.


The server's MSysConf table exists, but is in an incorrect format.  Contact your system administrator. (Error 3407)

The MSysConf table created on the server to help control communications between the Microsoft Jet database engine and the attached SQL database requires a very specific format.


Invalid field name 'name' in definition of index or relationship. (Error 3409)

Possible causes:

The field name you've specified might be misspelled.  Check the spelling of the field name.

You tried to update a Counter field, but Counter fields can't be updated.


Can't open this database for update. (Error 3410)

This database is temporarily in use by the system.  Wait a short time and then try to open the database again.


Invalid entry.  Can't perform cascading operation in table 'name' because value entered is too big for field 'name'. (Error 3411)

You're trying to save a value to a primary key field that's included in a relationship.  Because the Cascade Update Related Fields option is selected for the relationship, your application is attempting to update the matching field in the related table.

To save your changes to this field, the text you enter must be no longer than the field size of the related field that your application is trying to update for you.  In this case, the related field has a shorter field size than the field you're updating.  To avoid this problem in the future, set the Size property for both of the matching fields to the same value.


Can't perform cascading update on table 'name' because it is currently in use by user 'name' on machine 'name'. (Error 3413)

You're trying to save a value into a primary key field that's included in a relationship.  Because the Cascade Update Related Fields option is selected for this relationship, your application is attempting to update the matching field in the related table.

The matching field can't be updated because of a locking conflict with another user.  To save the record, you must wait until the related table is no longer in use.


Can't perform cascading update on table 'name' because it is currently in use. (Error 3414)

You're trying to save a value to a primary key field that's included in a relationship.  Because the Cascade Update Related Fields option is selected for this relationship, your application is attempting to update the matching field in the related table.

The matching field can't be updated because you have it open or locked on your computer.  To save the record, you must first close the related table.


Zero-length string is valid only in a text or Memo field. (Error 3415)

You're trying to enter a zero-length string in a field that has a data type other than Text or Memo.  You may be able to enter a Null value instead.


An action query cannot be used as a row source. (Error 3417)

Possible cause:

The query being used as a row (record) source is an action query or a data-definition query.


Can't open 'tablename'.  Another user has the table open using a different network control file or locking style. (Error 3418)

The Microsoft Jet database engine can't open an external Paradox table because of inconsistencies between your initialization settings and those of another user who currently has the table open.  The ParadoxNetPath and the ParadoxNetStyle options in the [Paradox ISAM] section of the Registry must be consistent for all users sharing a database.  Make sure your initialization settings match those of all other users sharing the database, and then try opening the table again.


Can't open this Paradox 4.x or 5.x table because ParadoxNetStyle is set to 3.x in the initialization setting. (Error 3419)

The Microsoft Jet database engine was unable to open an external Paradox table because of inconsistencies between the version of the table and your ParadoxNetStyle initialization setting in the [Paradox ISAM] section of the Registry.

To correct the problem

1.	Exit your application.

2.	In the [Paradox ISAM] section of the Registry, change the ParadoxNetStyle setting to 4.x.

The ParadoxNetStyle setting must be consistent for all users sharing a database.

3.	Restart your application.

4.	Try opening the table again.


Object is invalid or not set. (Error 3420)

You are attempting to reference an object that is no longer valid or has not been set.

Possible causes:

The object has been closed.

The object has been orphaned (the parent object has been closed or deleted).

You are trying to reference a method or property of the collection, but you haven't assigned it to a variable first.  For example, to reference the Name property, use the following:

Dim dbsPublish As Database

Set dbsPublish = OpenDatabase("BIBLIO.MDB")

dbname = dbsPublish.Name


Data type conversion error. (Error 3421)

The Microsoft Jet database engine was unable to convert data into the type required by a method or property.  This problem typically occurs if you use an argument of one type when a method or property expects another type.


Can't modify table structure.  Another user has the table open. (Error 3422)

The Microsoft Jet database engine was unable to modify the structure of a table because another user currently has the table open.  Wait until the table is closed, and then try making your changes again.


You cannot use ODBC to attach (link) an external Microsoft Access or ISAM database table to your database. (Error 3423)
You cannot use ODBC to import from, export to, or link an external Microsoft Access or ISAM database table to your database. (Error 3423)

You are attempting to link, import data from, or export data to either an external Microsoft Access table or an external ISAM database table (for example, dBASE, FoxPro, Paradox, or Btrieve), but you've selected <SQL Database> as the data source. You must select the appropriate data source for the data you're attempting to attach, or link.


The Microsoft Jet database engine has found a problem in your database.  To correct the problem, you must repair and compact the
The Microsoft Jet database engine has found a problem in your database.  To correct the problem, you must repair and compact the database. (Error 3428)

The database you are attempting to use has an unspecified problem and, as a result, it is marked as corrupt.

To correct the problem

1.	Close the database.

2.	Repair the database with the RepairDatabase method.  In Microsoft Access, you can also do this by choosing Tools / Database Utilities / Repair Database.

2.	Compact the database with the CompactDatabase method.  In Microsoft Access, you can also do this by choosing Compact Database from the File menu.

Important   Both steps are required.


Incompatible installable ISAM version. (Error 3429)

You attempted to use an older version of an installable ISAM with the current version of the Microsoft Jet database engine.  Rerun Setup to install the correct version of the installable ISAM.


While loading the Excel installable ISAM, OLE was unable to initialize. (Error 3430)

OLE Automation was unable to initialize while loading the Microsoft Excel installable ISAM.  Try reinstalling the OLE DLL files.


This is not an Excel 5 file. (Error 3431)

You attempted to read a file as a Microsoft Excel version 5 file, but the file isn't in this format.


Error opening an Excel 5 file. (Error 3432)

An OLE error occurred while opening a Microsoft Excel version 5 file.


Invalid parameter in [Excel ISAM] section of the initialization setting. (Error 3433)

One of the options in the [Excel ISAM] section of the initialization file or Registry isn't valid.  Edit the initialization file and be sure all the parameters are valid.


Can't expand named range. (Error 3434)

Nonempty cells were encountered while attempting to add rows to a Microsoft Excel version 5 named range.  These cells can't be overwritten by an append operation.


Cannot delete Excel cells. (Error 3435)

Data in the specified Microsoft Excel spreadsheet range of cells can't be deleted.  These cells may contain formulas, or they may be protected cells.


Failure creating file. (Error 3436)

An error occurred while attempting to create a Microsoft Excel or text file or Lotus installable ISAM.

Possible causes:

Insufficient disk space

Network failure


Excel spreadsheet is full. (Error 3437)

You tried to add new records to a Microsoft Excel version 3 or version 4 file, but the file is full.  Files of these types can hold a maximum of 16,384 records.


The data being exported does not match the format described in the SCHEMA.INI file. (Error 3438)

Make sure the data being exported matches the format described in the SCHEMA.INI file.


You attempted to attach or import a Microsoft Word mail merge file.  Although you can export such files, you cannot attach or im
You attempted to attach or import a Microsoft Word mail merge file.  Although you can export such files, you cannot attach or import them. (Error 3439)

You attempted to attach or import a Microsoft Word mail merge file.  Although you can export such files, you can't attach or import them.


An attempt was made to import or attach to an empty text file.  To import or attach a text file, the file must contain data. (Er
An attempt was made to import or attach to an empty text file.  To import or attach a text file, the file must contain data. (Error 3440)

You attempted to import or attach to an empty text file.  To import or attach a text file, the file must contain data.


In the text file specification 'name', the 'name' option is invalid. (Error 3442)

One of the options in the text file specification for the Text ISAM is invalid.  The specification can be set in a number of ways:

From Microsoft Access, these values are set in the Link Text Wizard.  You can also see them in the system tables MSysIMEXSpec and MSysIMEXColumns.

From other Jet host applications, these values are stored in the SCHEMA.INI file.


In the fixed-width specification 'name', the 'name' does not specify a width. (Error 3443)

The fixed-width parameter specified in the text file specification for the Text ISAM is invalid ro does not specify a column width.  The specification can be set in a number of ways:

From Microsoft Access, these values are set in the Link Text Wizard.

From other Jet host applications, these values are stored in the SCHEMA.INI file.


The fixed-width specification 'name' contains no column widths. (Error 3444)

No column width parameter is specified in the text file specification for the Text ISAMor the width is invalid.  The specification can be set in a number of ways:

From Microsoft Access, these values are set in the Link Text Wizard.

From other Jet host applications, these values are stored in the SCHEMA.INI file.


This query is not a properly formed data definition query. (Error 3357)
This query is not a properly formed data-definition query. (Error 3357)

This query is not a properly formed data-definition query.


'reserved error alert' (Error 3416)

This error was generated by an application released after this version of the Microsoft Jet database engine.


Cant have action query as input. (Error 3417)
Can't have action query as an input. (Error 3417)

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


Cant create database because Locale is invalid. (Error 3424)
Can't create database because Locale is invalid. (Error 3424)

An invalid locale parameter was specified.  Make sure you are using a valid Data Access Constant to specify the locale parameter.


Text file specification field seperator matches decimal seperator or text delimiter. (Error 3441)
Text file specification field seperator matches decimal separator or text delimiter. (Error 3441)

Two or more of the following delimiters settings used by the Text ISAM are the same:

TxtDelimiter

NumberDecimalSymbol

CurrencyDecimalSymbol

Format


Incorrect version of Jet DLL file was found. (Error 3445)

The installed Jet DLL (MSAJT200.DLL for 16-bit versions, or MSJT2032 for 32-bit versions) must be version 2.5 or later.  Try reinstalling the application that returned the error.


Jet VBA file not found. (Error 3446)

The Jet VBA file (VBAJET.DLL for 16-bit versions, or VBAJET32.DLL for 32-bit versions) could not be found.  Try reinstalling the application that returned the error.


The Jet VBA file failed to initialize when called. (Error 3447)

The Jet VBA file (VBAJET.DLL for 16-bit versions, or VBAJET32.DLL for 32-bit versions) did not initialize when it was called.  Try reinstalling the application that returned the error.


OLE system function call failed. (Error 3448)

An OLE Automation function called failed.  Try re-installing the application that returned the error.


No country code found in connect string for an attached (or linked) table. (Error 3449)

No country code was found in the connect string for an attached (or linked) table.


Data type mismatch in criteria expression. (Error 3464)

The criteria expression in a Find method is attempting to compare a field with a value whose data type does not match the field's data type.


Record length too long for an indexed Paradox table. (Error 3608)

An indexed Paradox table has a maximum record length of 1350 bytes.  Try reducing the size of some Text or Memo fields.


No unique index found for referenced field of primary table. (Error 3609)

When you create a relationship between tables, the referenced field in the primary table must have a unique index.  See the Index object and Primary property topics for more details on how to do this.


Same table referenced as both source and destination in make-table query. (Error 3610)

One of the source tables in a SELECT INTO statement is also named as the destination table.  Either remove the table from the source tables or rename the destination table.


Cant execute data definition statements on attached data sources. (Error 3611)
Can't execute data definition statements on attached data sources. (Error 3611)

The Microsoft Jet database engine cannot create an index on an attached (or linked) ISAM table, or on an ODBC table that already has a unique index.


Multi-level GROUP BY clause not allowed in a subquery. (Error 3612)

An SQL subquery cannot list more than one field in a GROUP BY clause.


Cant create a relationship on attached (or linked) SQL tables. (Error 3613)
Can't create a relationship on attached (or linked) SQL tables. (Error 3613)

The Microsoft Jet database engine cannot create a relationship on attached tables (or linked tables) in ODBC data source tables.


GUID not allowed in Find method criteria expression. (Error 3614)

The crieteria expression in a Find method cannot reference a GUID.


Type mismatch in JOIN expression. (Error 3615)

A JOIN expression is attempting to join two tables on columns of incompatible data types.


Updating data in an attached (or linked) table is not supported by this ISAM. (Error 3616)

The installable ISAM you are using does not allow updates to records in external tables.  You can add new records, though.


Deleting data in an attached (or linked) table is not supported by this ISAM.(Error 3617)

The installable ISAM you are using does not allow you to delete records in external tables.  You can add new records, though.


The ReplicaID Property is read-only and cannot be changed. (Error 3461)
The replication property you are attempting to set or delete is read-only and cannot be changed. (Error 3461)

Many properties related to replication are for internal use only or are available to the developer on a read-only basis.  Review your program code to make sure you are reading rather than changing the property.


The object cannot be made replicable because the database is not replicable. (Error 3486)
The object cannot be made replicable because the database is not replicable. (Error 3485)

You cannot make an object in a database replicable unless you first make the database it belongs to replicable.  You can make the database replicable by setting the Replicable property to True.

All objects in the database are made replicable when the database is made replicable, unless the KeepLocal property has been set on an object.


You cannot make changes to the design of the database at this replica. (Error 3452)

Changes to the design of a replicable database can be made only at the design-master replica.  The replica you are attempting to change is not the design-master.  Locate the design-master replica and make your changes there.


You cannot add a second ReplicationID Autonumber field to a table. (Error 3487)
You cannot add a second ReplicationID Autonumber field to a table. (Error 3486)

The table you are attempting to change already has one field that uses the ReplicationID Autonumber (or GUID) data type.  If you are attempting to create a second ReplicationID field to serve as a foreign key, use the Number data type instead of the Autonumber data type.


The database you are attempting to make replicable cannot be converted. (Error 3488)
The database you are attempting to make replicable cannot be converted. (Error 3487)

Only databases created with version 3.0 of the Microsoft Jet database engine can be made replicable.  Although you can open the database using an installable ISAM, you cannot convert it to a replicable form.  If the database was created using an earlier version of Microsoft Jet, convert the format to version 3.0.  If the database is in another format, export the data to a new Microsoft Jet database and retry.


You cannot establish or maintain an enforced relationship to a replicable table during this operation. (Error 3453)
You cannot establish or maintain a relationship to a replicable table during this operation. (Error 3453)

You are attempting to establish a relationship between a replicable table and a nonreplicable table.  Replication does not allow a relationship between:

A replicable table and a local table.

Two local tables that you are making replicable.

Two tables with different KeepLocal property settings.

Delete the relationship between the two tables before proceeding with the operation


The value specified is not a ReplicaID for any replica in the replica set. (Error 3489)
The value specified is not a ReplicaID for any replica in the replica set. (Error 3488)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


You cannot set the KeepLocal property for an object that is already replicable. (Error 3457)

The KeepLocal property cannot be set on a replicable object.  Setting a local object's KeepLocal property after the database has been converted into a replicable form has no effect on the object.  If you want to keep an object from being replicated to the other replicas in the set, set the object's Replicable property to False.


The replica you are attempting to exchange with is currently being used in another exchange. (Error 3510)

A replica can be involved in only one synchronization at a time.  Although you cannot initiate a second exchange while the replica is locked, you can continue using the replica.  Wait a few minutes and try your exchange again.


The Microsoft Jet database engine could not read the system clock on your computer. (Error 3515)

The Jet database engine uses your computer's system clock for certain internal processes.  It tried to read the computer's clock but was not able to.  Shut down and restart your computer.


Network IO error. (Error 3566)

The communication between your computer and the network is experiencing a problem.  Check to be sure your network is operating properly and that your network cable is tightly connected to your computer.  Shut down, turn off, and reboot your computer.


The replica has been logically removed from the replica set and is no longer available. (Error 3569)

The replica you are attempting to use has been removed because either 1) it has not been synchronized within the required number of days (retention period) or 2) the replica has been synchronized with two different design-master replicas.  The replica should be deleted from your computer.

If there is data in the replica that has not been synchronized with any other replica, manually enter that data in another replica in the set.  You can determine which records have unsynchonized data by examining the s_Generation field in each table.  A value of 0 in the s_Generation field indicates the record is new and has not been synchronized with another replica in the set.

If the replica is the design-master replica, compare the structure of the replica with another replica in the set to determine if there are any design changes that have not been synchronized.


A disk IO error occurred while reading or writing to the TEMP directory. (Error 3572)

There is a problem accessing the TEMP directory on your computer.  Check that the path to the TEMP directory is set properly.


Cannot make a new replica because the 'name' object in 'name' container could not be made replicable. (Error 3490)

The Microsoft Jet database engine was in the process of creating a replica.  The operation failed when it attempted to act on the object and container identified in the error message.


Cannot make the 'name' object replicable. (Error 3455)

The Microsoft Jet database engine was in the process of making the object replicable.  The operation failed because there were insufficient resources.  If the object is a table, make sure the total number of fields after replication does not exceed 255 and the total number of bytes in a record does not exceed 2048.


The database must be opened in exclusive mode before it can be made replicable. (Error 3491)

You attempted to make a database replicable after opening the database in shared mode.  Close the database and reopen it in exclusive mode, and then make it replicable.


The synchronization failed because a design change could not be applied to one of the replicas. (Error 3492)

The Microsoft Jet database engine attempted to update the database design at one of the replicas.  There are several possible reasons why the design could not be updated, including:

A replicable table might have the same name as an existing local table.

The object to be updated is already open at the replica.

Look in the MSysSchemaProb table for additional information regarding the synchronization failure.


The operation you attempted conflicts with an existing operation involving the replica. (Error 3460)

Another user or application is already performing the same operation on the replica.  Retry your action later.


Once a database has been made replicable, it cannot be made unreplicable. (Error 3459)

A database that has been made replicable (by setting its Replicable property to True) cannot be made unreplicable.  Setting the database Replicable property to False or any other value has no effect on the replicable database.  If you need to use a copy of the database that does not have the properties, fields, tables, and other characteristics associated with replication, open the backup copy of the database made before the database was first converted.


The KeepLocal property cannot be set on a database; it can be set only on the objects in a database. (Error 3458)

The KeepLocal property is set to True for objects in a database that you do not want made replicable.  You cannot set this property for the entire database.


Cannot make the 'name' object in 'name' container replicable. (Error 3456)

The Microsoft Jet database engine was in the process of making the object replicable.  The operation failed because there were insufficient resources to manipulate the object.  If the object is a table, make sure the total number of fields after replication does not exceed 255 and the total number of bytes in a record does not exceed 2048.  If the number of fields or characters is under the limit, decrease the size of the record.


The replica name or ID does not match a currently managed replica. (Error 3520)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


The two replicas cannot be synchronized because there is no common point to start the synchronization. (Error 3521)

Too much time has passed since these two replicas were last synchronized.  The Microsoft Jet database engine cannot find a common point of reference to begin applying changes in the content or structure of the database.


The name selected for the system object is already in use. (Error 3526)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


The wait period for an event has timed-out. (Error 3531)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


The system object used by a process still exists after the process has stopped. (Error 3533)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


The two replicas you are attempting to synchronize are from different replica sets. (Error 3545)

Replicas from different replica sets cannot be synchronized.  Make sure you have selected the proper replica for synchronization.


The type of exchange you are attempting is not valid. (Error 3546)

The requested exchange cannot be performed because of an invalid type parameter.  Use a valid exchange type in your program.


GUIDs do not match or the requested GUID could not be found. (Error 3548)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


The filename you provided is too long. (Error 3549)

Use a shorter filename.


The disk drive you are attempting to access is unreadable. (Error 3465)

If you are attempting to access a floppy disk, make sure the door to the disk drive is closed.  If you are attempting to access a hard disk, the disk might have a corrupted sector.


The disk drive you are attempting to write to is full. (Error ####)
The disk drive you are attempting to write to is full. (Error 3575)

There is not enough space on the disk drive to complete the operation.  Delete unneeded files from the disk to create sufficient space for the operation.  Make space available on the disk larger than the file you are attempting to save or otherwise manipulate.


The database you are attempting to open is already in use by another application. (Error ####)
The database you are attempting to open is already in use by another application. (Error 3576)

If you are attempting to open the database in Exclusive mode, it is possible that another application already has the database open.  If you are attempting to open the database in Shared mode, it is possible that another application has the database open in Exclusive mode.  Close the other applications using the database and try your request again.


Cannot find the .dll 'name'. (Error 3463)

Make sure that the specified .DLL is in your path.


Disk full for path 'name'. (Error 3472)

Remove files from the disk drive to free up space.


The object specified is not replicable because it is missing a necessary resource. (Error 3489)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


Can't retrieve the full path information for a replica. (Warning 3499)

This is an unexpected warning.  Please contact Microsoft Product Support Services for further information.


The size of the registry parameter exceeds the maximum allowed. (Error 3552)

Each parameter in the system registry has a maximum size.  The setting you attempted to use exceeded the allowed maximum.  Check the size limitation for the parameter you are setting.


The two replicas you are attempting to synchronize have the same ReplicaID. (Error 3560)

Use a different target replica to synchronize with your replica.


The two replicas you are attempting to synchronize both have design-master status. (Error 3561)

Delete one of the design-master replicas.


All valid nicknames for replicas are already in use. (Error 3555)

You have reached the maximum number of replicas (32,768) allowed in a replica set.  Start a new replica set.


The ReplicaID for this replica was reassigned during a move or copy procedure. (Warning 3574)

This is an unexpected warning.  Please contact Microsoft Product Support Services for further information.


Can't change a replicable database from allowing multiple data masters to allowing only a single data master. (Error 3593)

Whether a replicable database allows users to change data at all replicas (multiple data masters) or only at the design-master replica (single data master) is determined when the database is first converted into a replicable form.  After the database has been converted, the single/multiple data master attribute cannot be changed.


Can't change a replicable database from allowing only a single data master to allowing multiple data masters. (Error 3594)

Whether a replicable database allows users to change data only at the design-master replica (single data master) or at all replicas (multiple data masters) is determined when the database is first converted into a replicable form.  After the database has been converted, the single/multiple data master attribute cannot be changed.


Failure to write because destination disk is full. (Error 3559)

This is an unexpected error.  Please contact Microsoft Product Support Services for further information.


The system tables in your replica are no longer reliable and the replica should not be used. (Error 3595)

The replica on your computer is corrupted.  When the Microsoft Jet database engine repaired the replica, it may have altered one or more system tables.  Delete the replica and replace it with a new replica.


Synchronizing with a non-replicated database is not allowed. The ;name' database is not replicable. (Error 3605)
Synchronizing with a non-replicated database is not allowed. The 'name' database is not replicable. (Error 3605)

You are attempting to synchronize a replicated database with a nonreplicated database or to synchronize two nonreplicated databases.  Only replicas made from the same replicated database can be synchronized.

If one of the databases has already been replicated, create your second database as a replica from it.

If neither database has been replicated, select one of the databases to be used as the Design Master for the replica set. Do not attempt to replicate the second of the two original databases and then synchronize the two databases.  The second database must be a replica of the first for synchronization to succeed.


Insufficient memory to complete operation. (Error 3584)

Your computer ran out of memory while trying to replicate the database.  Close other applications on the computer and try the operation again.


Can't open replication system table 'name' because table is already in use. (Error 3623)

The system table needed to complete this operation is already in use.  Wait a few minutes and try your operation again.


Can't update replication system column. (Error 3577)

The column you are attempting to update is a system column and is read-only.


The replication property you are attempting to delete is read-only and cannot be removed. (Error 3607)

Check to be sure you are deleting the correct property.


You cannot make a password-protected database replicable or set password protection on a replicable database. (Error 3592)

If there is a database password set on the replica, remove the password.


The GUID could not be created. (Error 3553)

This is an unexpected error. Please contact Microsoft Product Support Services for further information.


There is no index on the GUID column. (Error 3550)

This is an unexpected error. Please contact Microsoft Product Support Services for further information.


AllPermissions Property

See Also	Applies To

Returns all the permissions that apply to the current UserName property of the Container or Document object, including permissions that are specific to the user as well as the permissions a user inherits from memberships in groups.

Syntax

object.AllPermissions

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

For any Container or Document object, the returned values may include the following:

Constant	Description

dbSecReadDef	Can read the table definition including column and index information.

dbSecWriteDef	Can modify or delete the table definition including column and index information.

dbSecRetrieveData	Can retrieve data from the Document.

dbSecInsertData	Can add records.

dbSecReplaceData	Can modify records.

dbSecDeleteData	Can delete records.

In addition, the Databases Container object or any Document object in a Documents collection may include the following:

Constant	Description

dbSecDBAdmin	Gives user permission to make a database replicable and change the database password.

dbSecDBCreate	Can create new databases (valid only on the Databases Container object in the system database [SYSTEM.MDW]).

dbSecDBExclusive	Exclusive access.

dbSecDBOpen	Can open the database.

Remarks

These constants are listed in the Data Access (DAO) object library in the Object Browser.

This property contrasts with the Permissions property, which returns only the permissions that are specific to the user and doesn't include any permissions that the user may also have as a member of groups.  If UserName is a group, then AllPermissions returns the same values as Permissions.


See Also

Permissions Property

UserName Property


 AllPermissions Method Applies To

Container Object

Document Object


ConflictTable Property

See Also	Example	Applies To

Returns the name of a side table containing the database records that conflicted during the synchronization of two replicas.  Returns a zero-length string if there is no side table or the database is nonreplicable.

Syntax

object.ConflictTable

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

If two users at two separate replicas each make a change to the same record in the database, the changes made by one user will fail to be applied to the other replica.  Consequently, the user with the failed change must address the problem in a process called "conflict resolution."

Conflict occurs at the record level, not between fields.  For example, if one user changes the Address field and another updates the Phone field in the same record, then one change is rejected.  Because conflict occurs at the record level, the rejection occurs even though the successful change and the rejected change are unlikely to result in a true conflict of information.

The exchange mechanism handles the record conflicts by creating conflict tables, which contain the information that would have been placed in the table, if the change had been successful.  Examine these conflict tables and work through them row by row, fixing whatever is appropriate.

All side tables are named xxxx _conflict, where xxxx is the original name of the table, truncated to the maximum table-name length.


ConflictTable Property Example

This example finds the name of the conflict table containing the records that were not updated during the replica synchronization, calls a custom routine for resolving the conflicts, deletes the record in the conflict table, and deletes the table after all records have been processed.

Sub Resolve (dbsResolve As Database)

Dim tdfTest As TableDef, rstConflict As Recordset

For Each tdfTest In dbsResolve.TableDefs

If (tdfTest.ConflictTable <> " ") Then

Set rstConflict = dbsResolve.OpenRecordset _

(tdfTest.ConflictTable)

rstConflict.MoveFirst	' Process each record.

While Not rstConflict.EOF

.

.	' Do conflict resolution.

.

rstConflict.Delete	' Remove conflicting.

rstConflict.MoveNext

Wend

rstConflict.Close

End If

Next tdfTest

End Sub


See Also

Resolving Synchronization Conflicts


ConflictTable Property Applies To

TableDef Object


GetRows Method

See Also	Example	Applies To

Retrieves multiple rows of a Recordset object into an array.

Syntax

myarray = object.GetRows (numrows)

The GetRows method syntax has the following parts:

Part	Description

myarray	The name of a Variant type variable to store the returned data.

object 	An object expression that evaluates to an object in the Applies To list.

numrows	The number of rows to retrieve.

Remarks

Use the GetRows method to copy one or more entire records from a Recordset.  GetRows returns a two-dimensional array.  The first subscript identifies the field and the second identifies the row number, as follows:

avarRecords(intField))(intRecord)

To get the first field value in the second row returned, use the following:

field1 = avarRecords(0,1)

To get the second field value in the first row, use the following:

field2 = avarRecords(1,0)

If more rows are requested than are available, then only the number available are returned.  Use the Ubound property to determine how many rows were actually fetched, as the array is sized to fit how many rows were returned.  For example, if you returned the results into a variant called varA, you could determine how many rows were actually returned by using:

numReturned = Ubound(varA,2) + 1

The + 1 is used because the first data returned is in the 0 element of the array.  The number of rows that can be fetched is constrained by available memory and should be chosen to suit your application [image] don't expect to use GetRows to bring your whole table into an array if it is a large table.

Because all fields of the recordset are returned in the array, including long memo and binary fields, you might want to use a query that restricts the columns returned.

After a call to GetRows, the current record is positioned at the next unread row; that is, GetRows has an equivalent positioning effect to Move numrows.

If you are trying to fetch all the rows using multiple GetRows calls, use the EOF property to be sure that you're at the end of the Recordset.  GetRows returns less than the number requested either at the end of the Recordset, or if it cannot fetch a row in the range requested.  For example, if a fifth record cannot be retrieved in a group of ten records that you're trying to fetch, GetRows returns four records and leaves the record that caused a problem as the current record.  It will not generate a run-time error.  This situation might occur if a record in a dynaset has been deleted by another user.


See Also

BOF, EOF Properties

FillCache Method

Move Method (Data Access)

Value Property (Data Access)


 GetRows Method Applies To

Recordset Object


GetRows Method Example

The following example uses an SQL statement to retrieve fields from a table and stores the selected records in a two-dimensional array.  Notice that you don't have to dimension or size the array; this is done automatically when GetRows returns records.  This example opens a forward-only-scrolling snapshot because the resulting Recordset will be used only to read data in a single pass.

Dim dbsCurrent As Database, rstEmployee As Recordset

Dim avarRecords As Variant

Dim intFields As Integer, intRows As Integer

dbsCurrent = CurrentDB()

Set rstEmployee = dbsCurrent.OpenRecordset("SELECT FirstName, " & _

"LastName, SSN FROM Employees", dbOpenSnapshot + _

dbForwardOnly)

intField = 0

intRecord = 0

avarRecords = rstEmployee.GetRows(50)

...

...	' Use intField and intRecord as array indexes to enumerate

...	' the returned records, locate particular values, and so on.


Inherit Property

See Also	Example	Applies To

Returns a value that determiness whether new Document objects will inherit a default Permissions property setting.

Syntax

object.Inherit

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Return Values

The return values are Boolean data type.

Remarks

Use the Inherit property in conjunction with the Permissions property to define what permissions new documents will automatically be given when they're created.  If you set the Inherit property to True, and then set a permission on a container, that permission will be set on every new document created in that container.  This is a very convenient way of presetting permissions on an object.

Setting the Inherit property will not affect existing documents in the container [image] you can't modify all the permissions on all existing documents in a container by setting the Inherit property and a new permission.  It will affect only new documents that are created after Inherit is set.


Inherit Property Example

This example sets the Table container's Inherit property to True, and then sets the Permissions property to allow users to alter the security settings of documents.

Dim dbsBiblio As Database, conTables As Container

Set dbsBiblio =  DBEngine.Workspaces(0).OpenDatabase("BIBLIO.MDB")

Set conTables = dbsBiblio.Containers("Tables")

conTables.Inherit = True

conTables.Permissions = dbSeeWriteSec


See Also

Document Object

Permissions Property


Inherit Property Applies To

Container Object


Synchronize Method

See Also	Applies To

Synchronizes the current replicable database object with the database in the .MDB file corresponding to pathname.  Various types of exchanges can be performed as specified by the exchange argument.  If no argument is provided, the exchange is bidirectional (import and export).

Syntax

database.Synchronize(pathname [,exchange])

The Synchronize method syntax has these parts:

Part	Description

database	The name of the replica that you want synchronized.

pathname	Path to the target database with which database will be synchronized.  This can include a Unicode or network directory name.  The trailing .MDB can be optionally omitted.

exchange	A constant indicating which direction to synchronize changes between the two databases.  This can be one of the following Integer constants:

  dbRepExportChanges [image] Send changes from current database to pathname.

  dbRepImportChanges [image] Receive changes from pathname.

  dbRepImExpChanges [image] (Default) Bidirectional exchange.

Remarks

This method causes an exchange of data and schema changes between the database and the .MDB identified by pathname.  Schema changes are always done first.  Both databases must be at the same schema level before data can be exchanged.  For example, an exchange of type dbRepExportChanges might cause schema changes to be made at the current replica even though data changes flow only from the current replica to the designated target.

The replica identified in pathname must be part of the same replica set.  If both replicas have the same ReplicaID property setting or have design-master status, the synchronization fails.


See Also

Synchronizing Replicas


Synchronize Method Applies To

Database Object


MakeReplica Method

See Also	Applies To

Makes a new replica based on the current replicable database using the supplied filename.

Syntax

database.MakeReplica(replica[, dbRepMakeReadOnly])

The MakeReplica method syntax has these parts:

Part	Description

database	The name of an existing, replicable Database object.

replica	The path and filename to be given the new replica.  If replica is an existing filename, the method fails and returns an error message.

Remarks

If dbRepMakeReadOnly is supplied, the replicable elements of the newly created database will not be modifiable.

As with most of the replication methods and properties, the database must be a replicable database for this method to work.


See Also

Making Additional Replicas


MakeReplica Method Applies To

Database Object


KeepLocal Property

See Also	Applies To

Returns or sets a value that indicates if an object is kept local to a replica.  You can only set this property before converting the database to a replicable form.

Syntax

object.KeepLocal [= boolean]

The KeepLocal property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether the object is kept local to the replica, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The object is kept local to the replica.

False	(Default) The object is converted to a replicable object.

Remarks

When a nonreplicable database is converted to a replicable form, all the objects in the database are converted to replicable objects unless you indicate otherwise.  Prior to converting your database, you can create and set the KeepLocal property on the object you do not want made replicable.  For example, if your database had a table containing confidential personnel information, such as salaries, you can set that table's KeepLocal to True to keep it local while all other objects are made replicable when the database is made replicable.  The KeepLocal property cannot be applied to objects after they have been converted into a replicable form.

After a database is made replicable, all new objects created at the design-master replica or any other replica in the set are treated as local objects.  Local objects remain at the replica where they were created and are not propagated around the replica set.  Each time you make a new replica in the set, all the replicable objects at the source replica are included in that new replica, but none of the local objects are included.

There may be instances when you create a new object at a replica and want to change it from local to replicable so that all end users could have it.  To change an object from local to replicable, you must either create the object at, or import it into, the design-master replica.  After the object is part of the design-master replica, you must set the object's Replicable property to True.

Warning   The object on which you are setting the KeepLocal or Replicable property might have already inherited that property from another object.  However, the value set by the other object has no affect on the behavior of the object you want to KeepLocal or make Replicable.  You must directly set the property for each object.


See Also

Converting a Database into a Replicable Form

Keeping Objects Local Prior to Converting a Database into a Replicable Form

Making Objects Replicable or Local

Replicable Property

ReplicaID Property


KeepLocal Property Applies To

Database Object


Replicable Property

See Also	Applies To

Database [image] returns or sets a value that adds fields, tables, and properties to your database and makes the database replicable.

Objects [image] returns or sets a value that changes an object from local to replicable after you create it in or import it into the design-master replica.

Syntax

object.Replicable [= boolean]

The Replicable property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

boolean	A Boolean expression specifying whether to replicate a database or local object, as described in Settings.

Settings

The settings for boolean are:

Setting	Description

True	The database or local object is replicable.

False	(Default) The database or local object isn't replicable.

Remarks

Once you set the property to True for a database, it cannot be changed.  If you then try to set the property to False, an error message is returned.

There may be instances when you create a new object (such as a table, query, form, report, macro, or module) at a replica and want to change it from local to replicable so that all end users could have it.  To change an object from local to replicable, you must either create the object at, or import it into, the design-master replica.  After the object is part of the design-master replica, you must set the object's Replicable property to True.

Warning   The object on which you are setting the KeepLocal or Replicable property might have already inherited that property from another object.  However, the value set by the other object has no affect on the behavior of the object you want to keep local or make replicable.  You must directly set the KeepLocal or Replicable property for each object.


See Also

Converting a Database into a Replicable Form

KeepLocal Property

Making a Replica the Design-Master for the Replica Set

Making Additional Replicas

Making Objects Replicable or Local

ReplicaID Property


Replicable Property Applies To

Database Object


ReplicaID Property

See Also	Applies To

Returns a 16-byte, OLE 2 GUID, created by the Microsoft Jet database engine, that provides the replica with a unique identification.

Syntax

object.ReplicaID

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The ReplicaID property can be used along with the DesignMasterID property to change the design master of the replica set.


See Also

KeepLocal Property

Moving Design-Master Status to Another Replica

Replicable Property

DesignMasterID Property


ReplicaID Property Applies To

Database Object


DesignMasterID Property

See Also	Applies To

Returns or sets a 16-byte, OLE 2 GUID, created by the Microsoft Jet database engine, that uniquely identifies the design-master replica in a replica set.

Syntax

object.DesignMasterID [= value]

The DesignMasterID property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

value	A 16-byte ReplicaID identifying the database object to be identified as the design-master.

Remarks

The DesignMasterID setting is stored in the MSysReplicas system table.  Setting DesignmasterID to the ReplicaID setting of another database gives that database design-master status in the replica set, as shown in the following code example:

' Open the current design-master in exclusive mode.

Set dbs = DBEngine(0).OpenDatabase(strOldDM, True)

' Open the new design-master.

set newdmdb = DBEngine(0).OpenDatabase(strNewDB)

dbs.DesignmasterID = newdmdb.ReplicaID

dbs.Synchronize strNewDB,dbRepImpExpChanges

dbs.Close

newdmdb.Close

Warning   This property should be set only on the current design-master replica.  Setting this property on a replica, when there is already another design-master replica, can partition your replica set into two irreconcilable sets and prevent any further synchronization of data. You can set the property on another replica only if the original design-master replica is lost or erased.  This will designate the current replica as the new design-master.


See Also

KeepLocal Property

Moving Design-Master Status to Another Replica

Making a Replica the Design-Master for the Replica Set

ReplicaID Property

Replicable Property


DesignMasterID Property Applies To

Database Object


DataMode Property

See Also	Applies To

Sets a value specifying whether the DBGrid operates in bound or unbound mode.  This property is not available at run time.

Settings

The settings for the DataMode property are:

Setting	Description

0	The DBGrid displays data available from the bound data source.

1	The DBGrid uses the unbound control events to retrieve and update displayed data.

Remarks

When the DBGrid is bound to a data source, setting the DataMode to 1 results in an error.


See Also

RowBuffer Object

UnboundAddData Event

UnboundDeleteRow Event

UnboundReadData Event

UnboundWriteData Event


DataMode Property Applies To

DBGrid Control


CachePages Property

See Also	Applies To

Returns or sets the number of pages of data the DBGrid keeps in memory before retrieving data from the Data control or unbound control events.

Syntax

object.CachePages [= pages]

The CachePages property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pages	An integer specifying the number of pages of data.  Default value is 3 pages.

Remarks

In general, the number of rows of data contained in a page is the number of pages you determine with the pages argument, times 10 (each page contains 10 rows).  For example, 3 pages might contain 30 rows (3 pages x 10 rows).  This number can vary, however, if you are at or near the beginning or end of a file, as either the beginning or ending page may contain less than 10 rows.


See Also

UnboundAddData Event

UnboundDeleteRow Event

UnboundReadData Event

UnboundWriteData Event


CachePages Property Applies To

DBGrid Control


UnboundAddData Event

See Also	Example	Applies To

Occurs in an unbound DBGrid control when a new row is added to it.  This event alerts your application that it must add a new row of data to its database.

Syntax

Private Sub object.UnboundAddData(rowbuf As RowBuffer, newrowbookmark As Variant)

The UnboundAddData event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

rowbuf 	The RowBuffer object which contains the retrieved row of data.

newrowbookmark	A bookmark which acts as a unique identifier for each row of data.

Remarks

The number of rows to be retrieved is determined by the RowCount property, which is always set to a value of 1 in this event, because you can add only one row at a time.

A new row of data can be added to the dataset only if the AllowAddNew property is True.

The rowbuf argument contains a single row of data to be written to the dataset. Before returning from this event, newrowbookmark must be set to the bookmark of the newly added row.


UnboundAddData Event Applies To

DBGrid Control


See Also

AllowAddNew Property

Bookmark Property (DBGrid)

RowBuffer Object

RowCount Property

UnboundDeleteRow Event

UnboundReadData Event

UnboundWriteData Event


DataMode Property Example
UnboundAddData Event Example

This example illustrates the use of the UnboundAddData event to add a row of data to a database, in this case, a simple array.

Private Sub DBGrid1_UnboundAddData(ByVal RowBuf As RowBuffer, NewRowBookmark As Variant)

    RowCount = RowCount + 1

    ReDim Preserve UserData(MAXCOLS, RowCount) 'The array database.

    NewRowBookmark = RowCount 'Sets the bookmark to the last row.

 ' The following loop adds a new record to the database.

    For i% = 0 To MAXCOLS - 1

        If Not IsNull(RowBuf.Value(0, i%)) Then

            UserData(i%, RowCount - 1) = RowBuf.Value(0, i%)

        End If

    Next i%

End Sub


UnboundDeleteRow Event

See Also	Example	Applies To

Occurs whenever a row of data is deleted from the unbound DBGrid. This event alerts your application that it must delete a row of data from its database.

Syntax

Private Sub object.UnboundDeleteRow(bookmark As Variant)

The UnboundDeleteRow event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

bookmark 	A value representing the bookmark of the row to be deleted.

Remarks

The bookmark argument must be set to the bookmark value provided when the row was retrieved with the UnboundReadData event or added by the UnboundAddData event.


See Also

Bookmark Property (DBGrid)

UnboundAddData Event

UnboundReadData Event

UnboundWriteData Event


UnboundDeleteRow Event Applies To

DBGrid Control


DataMode Property Example
UnboundDeleteRow Event Example

This example illustrates the use of the UnboundDeleteRow event to delete a row of data from a database, in this case, a simple array.

Private Sub DBGrid1_UnboundDeleteRow(Bookmark As Variant)

    For i% = Bookmark + 1 To RowCount - 1 ' Set next bookmark to 	 ' previous row.

        For j% = 0 To MAXCOLS - 1

            UserData(j%, i% - 1) = UserData(j%, i%)

        Next j%

    Next i%

    RowCount = RowCount - 1

End Sub


UnboundReadData Event

See Also	Example	Applies To

Occurs whenever an unbound DBGrid control requires data for display, such as when you scroll the DBGrid display.

Syntax

Private Sub object.UnboundReadData(rowbuf As RowBuffer, startlocation As Variant, readpriorrows As Boolean)

The UnboundReadData event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

rowbuf 	The RowBuffer object that will contain the retrieved data.  The number of rows to be retrieved is determined by the RowCount property.

startlocation 	A bookmark which specifies the row immediately before (in the case of forward fetching) or after (in the case of reverse fetching) the rows to be retrieved.  If startlocation is null, then forward fetching occurs from the beginning of the data set, while reverse fetching begins at the end of the data set.

readpriorrows 	True if data is to be retrieved in a forward direction, False if data is to be retrieved in a reverse direction.

Remarks

Once the data is retrieved, it is stored in the DBGrid's cache.  The amount of data cached depends upon the CachePages setting.

It is not necessary to fill the row buffer completely, and it is in fact acceptable to return no rows at all.  The value of the RowCount property of the RowBuffer object can be set to indicate that fewer rows were returned than requested.  The DBGrid interprets this to mean that there are no more rows to retrieve in the indicated direction.  Thus, it is only necessary to fill the row buffer completely if there are more valid rows to be retrieved.

For each row retrieved, you must provide a bookmark, which can later be used to refer to that row.  This bookmark is specified by setting the Bookmark property of the RowBuffer object for each row returned.  The data itself is specified by setting the Value property of the RowBuffer object for each column of data in each row returned.


See Also

Bookmark Property (DBGrid)

CachePages Property

RowBuffer Object

UnboundAddData Event

UnboundDeleteRow Event

UnboundWriteData Event

Value Property (RowBuffer Object)


UnboundReadData Event Applies To

DBGrid Control


DataMode Property Example
UnboundReadData Event Example

This example illustrates the use of the UnboundReadData event to read a row of data from a database, in this case, a simple array.

Private Sub DBGrid1_UnboundReadData(ByVal RowBuf As RowBuffer, StartLocation As Variant, ByVal ReadPriorRows As Boolean)

    rowsFetched% = 0

    If ReadPriorRows Then

        incr% = -1

    Else

        incr% = 1

    End If

    If IsNull(StartLocation) Then

        If ReadPriorRows Then

            curRow% = RowCount - 1

        Else

            curRow% = 0

        End If

    Else

        curRow% = StartLocation + incr%

    End If

    For i% = 0 To RowBuf.RowCount - 1

        If curRow% < 0 Or curRow% >= RowCount Then Exit For

        For j% = 0 To 3

            RowBuf.Value(i%, j%) = UserData(j%, curRow%)

        Next j%

        RowBuf.Bookmark(i%) = curRow%

        curRow% = curRow% + incr%

        rowsFetched% = rowsFetched% + 1

    Next i%

    RowBuf.RowCount = rowsFetched%

End Sub


UnboundWriteData Event

See Also	Example	Applies To

Occurs when an unbound DBGrid control has an entire row of modified data to write to the database.  It alerts your application that it must update an edited existing row of data to its database.

Syntax

Private Sub object.UnboundReadData(rowbuf As RowBuffer, writelocation As Variant)

The UnboundWriteData event syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

rowbuf 	The RowBuffer object that contains the modified row of data.

writelocation	A value that identifies the unique bookmark of the row of data as specified in the UnboundReadData and UnboundWriteData events.

Remarks

The value of the RowCount property of the RowBuffer object will always be 1, because you can update only one row of data at a time.

To cancel the UnboundWriteData event, set the RowCount property of the RowBuffer object to 0.  This signals the DBGrid that the write attempt failed.


See Also

Bookmark Property (DBGrid)

RowBuffer Object

RowCount Property

UnboundAddData Event

UnboundDeleteRow Event

UnboundReadData Event


UnboundWriteData Event Applies To

DBGrid Control


DataMode Property Example
UnboundWriteData Event Example

This example illustrates the use of the UnboundReadData event to read a row of data from a database, in this case, a simple array.

Private Sub DBGrid1_UnboundWriteData(ByVal RowBuf As RowBuffer, WriteLocation As Variant)

    s$ = "UnboundWriteData: " & WriteLocation

    Debug.Print s$

    For i% = 0 To MAXCOLS - 1

        If Not IsNull(RowBuf.Value(0, i%)) Then

            UserData(i%, WriteLocation) = RowBuf.Value(0, i%)

        End If

    Next i%

End Sub


RowBuffer Object

See Also	Properties

The RowBuffer object is used to contain one or more rows of retrieved data and transfer it between your application and an unbound DBGrid control.

Note  The RowBuffer object is not a derivable object which can be used by other applications.  It is an internal class usable only by unbound DBGrid controls.

Syntax

DBGrid.RowBuffer

Remarks

A RowBuffer is used in the following circumstances:

The RowBuffer object is passed as an argument to the UnboundReadData event, where one or more rows of data are placed in the RowBuffer object, which the DBGrid uses to fill its cache with data.

When data is updated in the DBGrid, the RowBuffer object is passed to the UnboundWriteData event.  Only one row of data is updated at a time, and the row updated is supplied with the original bookmark provided when the row was retrieved.

When a new row is added, the newly-added data is placed in the RowBuffer object and passed to the UnboundAddData event.

In all of the these cases, the RowBuffer object is passed to you by the unbound DBGrid control.  It is incumbent upon you and your application to add this data to your database (when passed by the UnboundReadData event) or update existing data in your database (when passed by the UnboundWriteData, UnboundAddData, or UnboundDeleteRow events).


See Also

RowCount Property

UnboundAddData Event

UnboundDeleteRow Event

UnboundReadData Event

UnboundWriteData Event


RowBuffer Object Properties

RowCount Property

ColumnCount Property

Bookmark Property

ColumnName Property

Value Property


Bookmark Property (DBGrid)

See Also	Example	Applies To

Returns or sets a bookmark for the specified row within a RowBuffer object in an unbound DBGrid control.

Syntax

object.Bookmark (row) [= value]

The Bookmark property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

row	An integer specifying the the row where the bookmark is placed. The range of this value can be from 0 to RowCount - 1.

value	A variant representing the bookmark for the specified row.

Remarks

A bookmark contains a user-defined value that is used to uniquely identify each row of data. It is passed in unbound events which require you to make changes to your database.

In the UnboundReadData event, there may be multiple rows, so you must provide a bookmark for each row.

The UnboundWriteData event passes a bookmark to you to identify the row of data to be updated.

The UnboundAddData event passes a bookmark to you to identify the row of data to be added.


See Also

Bookmark Property (DBGrid)

RowCount Property

UnboundAddData Event

UnboundReadData Event

UnboundWriteData Event


Bookmark Property Applies To

DBGrid Control

RowBuffer Object


Bookmark Property (DBGrid) Example

In this example, when the user deletes a row in the unbound DBGrid control, the UnboundDeleteRow event is triggered, allowing you to manually delete the row from your database, in this case, a simple array. The following code fragment shows how a bookmark is passed as an argument in the UnboundDeleteRow event to identify the row to be deleted.

Private Sub DBGrid1_UnboundDeleteRow(Bookmark As Variant)

    For i% = Bookmark + 1 To RowCount - 1

        For j% = 0 to MAXCOLS - 1

            UserData(j%, I% - 1) = UserData(j%, I%)

        Next j%

    Next I%


ColumnName Property

See Also	Applies To

Returns the name of the specified column within a RowBuffer object in an unbound DBGrid control.

Syntax

object.ColumnName (column)

The ColumnName property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

column	A string specifying the column for which you want the name.

Remarks

Enables you to obtain the name of a specified column.


See Also

Bookmark Property (DBGrid)

RowCount Property

UnboundAddData Event

UnboundReadData Event

UnboundWriteData Event


ColumnName Property Applies To

RowBuffer Object


ColumnCount Property

See Also	Applies To

Returns the number of columns present in a RowBuffer object in an unbound DBGrid control.

Syntax

object.ColumnCount

The object placeholder represents an object expression that evaluates to an object in the Applies To list.


See Also

ColumnName Property

DBGrid Control

RowCount Property


ColumnCount Property Applies To

RowBuffer Object


RowCount Property

See Also	Example	Applies To

Returns or sets the number of rows contained in the RowBuffer object in an unbound DBGrid control.

Syntax

object.RowCount [= number]

The RowCount property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

number	A long integer indicating the number of rows.

Remarks

In the UnboundWriteData event, this property specifies how many rows will be written, and is always set to a value of 1, since you can write only one row of data at a time. You can set this property to a value of 0, however, to indicate that the write operation failed.

In the UnboundAddData event, this property is always set to a value of 1, since only a single row can be added at a time. You can set this property to a value of 0, however, to indicate that the add operation failed.

In the UnboundReadData event, this property indicates how many rows have been requested to be filled. After filling those rows, you should set RowCount to the number of rows actually stored in the RowBuffer object.


See Also

RowBuffer Object

UnboundAddData Event

UnboundReadData Event

UnboundWriteData Event


RowCount Property Applies To

RowBuffer Object


DataMode Property Example
RowCount Property Example

In this example, the RowCount property of the RowBuffer object is checked to see whether or not the next line should be performed.

For i% = 0 To RowBuf.RowCount - 1

   If curRow% < 0 Or curRow% >= RowCount Then Exit For


Value Property (RowBuffer)

See Also	Example	Applies To

Returns or sets the value of an item of data within the RowBuffer object in an unbound DBGrid control.

Syntax

object.Value (row, column) [= value]

The Value property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

row	An integer from from 0 to RowCount - 1 indicating the row number of the item.

column	An integer from from 0 to ColumnCount - 1 indicating the column number of the item.

value	A variant value entered or displayed in the cell specified by row and column.

Remarks

The RowBuffer object can contain several columns and several rows of data.

In the UnboundWriteData and UnboundAddData events, the user enters the setting of the Value property into the unbound DBGrid control.  You then use this value to update your database.

In the UnboundReadData event, you supply the values of the row and column arguments requested by the unbound DBGrid control.


See Also

DBGrid Control

UnboundAddData Event

UnboundReadData Event

UnboundWriteData Event


Value Property (RowBuffer) Applies To

RowBuffer Object


Value Property (RowBuffer) Example

This example illustrates how a previously read row, contained in the Value property, is added to a database; in this case, a simple array.  In the following code fragment, if the RowBuffer object contains a row (Not IsNull), the row is written to the database.

For i% = 0 To MAXCOLS - 1

   If Not IsNull(RowBuf.Value(0, i%)) Then

      UserData(i%, RowCount - 1) = RowBuf.Value(0, i%)

   End If

Next i%


Array Function

See Also	Example

Returns a Variant containing an array.

Syntax

Array(arglist)

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

Remarks

Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the way the array elements are accessed is the same.  The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element.  In the following example, the first statement creates a variable A as a Variant.  The second statement assigns an array to variable A.  The final statement illustrates how to assign the value contained in the second array element to another variable.

Dim A As Variant

A = Array(10,20,30)

B = A(2)

The lower bound of an array created using the Array function is determined by the lower bound specified with the Option Base statement.

Note   A Variant not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types.


See Also

Deftype Statements

Dim Statement

Let Statement

Option Base Statement

Variant Data Type


Const Statement

See Also	Example

Declares constants for use in place of literal values.

Syntax

[Public | Private] Const constname [As type] = expression

The Const statement syntax has these parts:

Part	Description

Public	Used at module level to declare constants that are available to all procedures in all modules.  Not allowed in procedures.

Private	Used at module level to declare constants that are available only within the module where the declaration is made.  Not allowed in procedures.

constname	Name of the constant; follows standard variable naming conventions.

type	Data type of the constant; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant.  Use a separate As type clause for each constant being declared.

expression	Literal, other constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Constants are private by default.  Within procedures, constants are always private; their visibility can't be changed.  In standard modules, the default visibility of module-level constants can be changed using the Public keyword.  In class modules, however, constants can only be private and their visibility can't be changed using the Public keyword.

You can combine several constant declarations on the same line by separating each constant assignment with a comma.  If constant declarations are combined in this way, the Public or Private keyword, if used, applies to all of them.

You can't use 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 easy to modify.  Unlike variables, constants can't be inadvertently changed while your program is running.

If you don't explicitly declare the constant type (using As type), the constant is given the data type that is most appropriate for the expression provided.

Constants declared in Sub, Function, or Property procedures are local to that procedure.  A constant declared outside a procedure is defined throughout the module in which it is declared.   You can use constants anywhere you can use an expression.


See Also

#Const Directive

Deftype Statements

Function Statement

Let Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Declare Statement

See Also	Example

Used at module level to declare references to external procedures in a dynamic-link library (DLL).

Syntax 1

[Public | Private ] Declare Sub name Lib "libname" [Alias "aliasname" ][([arglist])]

Syntax 2

[Public | Private ] Declare Function name Lib "libname" [Alias "aliasname" ] [([arglist])][As type]

The Declare statement syntax has these parts:

Part	Description

Public	Used to declare procedures that are available to all other procedures in all modules.

Private	Used to declare procedures that are available only within the module where the declaration is made.

Sub	Indicates that the procedure doesn't return a value.

Function	Indicates that the procedure returns a value that can be used in an expression.

name	Any valid procedure name.

Lib	Indicates that a DLL contains the procedure being declared.  The Lib clause is required for all declarations.

libname	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 keyword.  You can also use Alias when a DLL procedure has the same name as a public 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 by the DLL naming convention.

aliasname	Name of the procedure in the DLL.

If the first character is not a #, aliasname is the name of the procedure's entry point in the DLL.  If # is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.

arglist	List of variables representing arguments that are passed to the procedure when it is called.

type	Data type of the value returned by a Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part	Description

Optional	Indicates that an argument is not required.  If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword.  All Optional arguments must be Variant.  Optional can't be used for any argument if ParamArray is used.

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

ParamArray	Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements.  The ParamArray keyword allows you to provide an arbitrary number of arguments.  May not be used with ByVal, ByRef, or Optional.

varname	Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.

type	Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

For Function procedures, the data type of the procedure determines the data type it returns.  You can use an As clause following the arglist to specify the return type of the function.  Within arglist you can use an As clause to specify the data type of any of the arguments passed to the procedure.  In addition to specifying any of the standard data types, you can specify As Any in the arglist to inhibit type checking and allow any data type to be passed to the procedure.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that Visual Basic should 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" ()

If you include an argument list, 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 As Long)

Notes   You can't have fixed-length strings in the argument list of a Declare statement [image] 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.

A constant, vbNullString, is provided by Visual Basic for use when calling external procedures, where the external procedure requires a string whose value is zero.  This is not the same thing as a zero-length ("") string.

In the 32-bit version of Microsoft Windows, dynamic-link library (DLL) procedure names are case-sensitive; those in the 16-bit version of Microsoft Windows (3.1 and earlier) are not.


See Also

Call Statement

Function Statement

Sub Statement


Deftype Statements

See Also	Example

Used at module level to set the default data type for variables, arguments passed to procedures, and the return type for Function and Property Get procedures whose names start with the specified characters.

Syntax

DefBool letterrange[, letterrange] . . .

DefByte letterrange[, letterrange] . . .

DefInt letterrange[, letterrange] . . .

DefLng letterrange[, letterrange] . . .

DefCur letterrange[, letterrange] . . .

DefSng letterrange[, letterrange] . . .

DefDbl letterrange[, letterrange] . . .

DefDate letterrange[, letterrange] . . .

DefStr letterrange[, letterrange] . . .

DefObj letterrange[, letterrange] . . .

DefVar letterrange[, letterrange] . . .

The argument letterrange has the following syntax:

letter1[-letter2]

The letter1 and letter2 arguments specify the name range for which you can set a default data type.  Each argument represents the first letter of the variable, argument, Function procedure, or Property Get procedure name and can be any letter of the alphabet.  The case of letters in letterrange isn't significant.

Remarks

The statement name determines the data type:

Statement	Data Type

DefBool	Boolean

DefByte	Byte

DefInt	Integer

DefLng	Long

DefCur	Currency

DefSng	Single

DefDbl	Double

DefDate	Date

DefStr	String

DefObj	Object

DefVar	Variant

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 module where it is used.  For example, a DefInt statement in one module affects only the default data type of variables, arguments passed to procedures, and the return type for Function and Property Get procedures declared in that module; the default data type of variables, arguments, and return types in other modules is unaffected.  If not explicitly declared with a Deftype statement, the default data type for all variables, all arguments, all Function procedures, and all Property Get procedures is Variant.

When you specify a letter range, it usually defines the data type for variables that begin with letters in the first 128 characters of the character set.  However, when you specify the letter range A [image] 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 character set (128 [image] 255).

Once the range A [image] Z has been specified, you can't 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 specify the data type of any variable, defined or not, using a Dim statement with an As type clause.  For example, you can use the following code at module level to define a variable as a Double even though the default data type is Integer:

DefInt A-Z

Dim TaxRate As Double

Deftype statements don't affect elements of user-defined types since the elements must be explicitly declared.


See Also

Character Set

Function Statement

Let Statement

Property Get Statement


Dim Statement

See Also	Example

Declares variables and allocates storage space.

Syntax

Dim varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] type]] . . .

The Dim statement syntax has these parts:

Part	Description

varname	Name of the variable; follows standard variable naming conventions.

subscripts	Dimensions of an array variable; up to 60 multiple dimensions may be declared.  The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement.  The lower bound is zero if no Option Base statement is present.

New	Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object.  The New keyword can't be used to declare variables of any intrinsic data type and can't be used to declare instances of dependent OLE Automation objects.

type	Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable you declare.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module.  At the procedure level, variables are available only within the procedure.

Use the Dim statement at module or procedure level to declare the data type of a variable.  For example, the following statement declares a variable as an Integer.

Dim NumberOfEmployees As Integer

Also use a Dim statement to declare the object type of a variable.  The following declares a variable for a new instance of a worksheet.

Dim X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare a dynamic array.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you do not specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip   When you use the Dim statement in a procedure, it is a generally accepted programming practice to put the Dim statement at the beginning of the procedure.


See Also

Array Function

Option Base Statement

Private Statement

Public Statement

ReDim Statement

Set Statement

Static Statement

Type Statement


Erase Statement

See Also	Example

Reinitializes the elements of fixed-size arrays and deallocates dynamic-array storage space.

Syntax

Erase arraylist

The arraylist argument is one or more comma-delimited array variables to be erased.

Remarks

It is important to know whether an array is fixed-size (ordinary) or dynamic because Erase behaves differently depending on the type of array.  Erase recovers no memory for fixed-size arrays.  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.

Erase frees the memory used by dynamic arrays.  Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.


See Also

Array Function

Dim Statement

Nothing Keyword

Private Statement

Public Statement

ReDim Statement

Static Statement


Function Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Public | Private] [Static] Function name [(arglist)] [As type]
[statements]
[name = expression]
[Exit Function]
[statements]
[name = expression]
End Function

The Function statement syntax has these parts:

Part	Description

Public	Indicates that the Function procedure is accessible to all other procedures in all modules.

Private	Indicates that the Function procedure is accessible only to other procedures in the module where it is declared.

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, even if they are used in the procedure.

name	Name of the Function; follows standard variable naming conventions.

arglist	List of variables representing arguments that are passed to the Function procedure when it is called.  Multiple variables are separated by commas.

type	Data type of the value returned by the Function procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, Variant, or any user-defined type.  Arrays of any type can't be returned, but a Variant containing an array can.

statements	Any group of statements to be executed within the body of the Function procedure.

expression	Return value of the Function.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )][As type]

Part	Description

Optional	Indicates that an argument is not required.  If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword.  All Optional arguments must be Variant.  Optional can't be used for any argument if ParamArray is used.

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

ParamArray	Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements.  The ParamArray keyword allows you to provide an arbitrary number of arguments.  It may not be used with ByVal, ByRef, or Optional.

varname	Name of the variable representing the argument; follows standard variable naming conventions.

type	Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Function procedures are public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function keywords cause an immediate exit from a Function procedure.  Program execution continues with the statement following the statement that called the Function procedure.  Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments.  However, unlike a Sub procedure, you can use a Function procedure on the right-hand side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression.  See the Call statement for specific information on how to call Function procedures.

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 keyword is usually not used with recursive Function procedures.

To return a value from a function, assign the value to the function name.  Any number of such assignments can appear anywhere within the procedure.  If no value is assigned to name, the procedure returns a default value: a numeric function returns 0, a string function returns a zero-length string (""), and a Variant function returns Empty.  A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following example shows how to assign a return value to a function named BinarySearch.  In this case, False is assigned to the name to indicate that some value was not found.

Function BinarySearch(. . .) As Boolean

. . .

' Value not found. Return a value of False.

If lower > upper Then

BinarySearch = False

Exit Function

End If

. . .

End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not.  Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution   A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the module level has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name.  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

Call Statement

Dim Statement

Nothing Keyword

Option Explicit Statement

Property Get Statement

Property Let Statement

Property Set Statement

Set Statement

Static Statement

Sub Statement


LBound Function

See Also	Example

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

Syntax

LBound(arrayname[, dimension])

The LBound function syntax has these parts:

Part	Description

arrayname	Name of the array variable; follows standard variable naming conventions.

dimension	Whole number indicating which dimension's lower bound is returned.  Use 1 for the first dimension, 2 for the second, and so on.  If dimension is omitted, 1 is assumed.

Remarks

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

LBound returns the values 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, Private, Public, ReDim, or Static statement can have any integer value as a lower bound.


See Also

Dim Statement

Option Base Statement

Private Statement

Public Statement

ReDim Statement

Static Statement

UBound Function


Let Statement

See Also	Example

Assigns the value of an expression to a variable or property.

Syntax

[Let] varname = expression

The Let statement syntax has these parts:

Part	Description

varname	Name of the variable or property; follows standard variable naming conventions.

expression	Value assigned to the variable or property.

Remarks

To simplify Visual Basic code, the optional Let keyword is most often omitted.

A value expression can be assigned to a variable or property only if it is of a data type that is compatible with the variable.  You can't assign string expressions to numeric variables, and you can't assign numeric expressions to string variables.  If you do, an error occurs at compile time.

Variant variables can be assigned either string or numeric expressions.  However, the reverse is not always true.  Any Variant except a Null can be assigned to a string variable, but only a Variant whose value 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.  Use the Set statement to assign object references to variables.


See Also

Const Statement

Data Type Summary

IsNumeric Function

LSet Statement

Set Statement

Variant Data Type


Option Base Statement

See Also	Example

Used at module level to declare the default lower bound for array subscripts.

Syntax

Option Base {0 | 1}

Remarks

If used, the Option Base statement must appear in a module before any statements that declare variables or define constants.

Since the default base is 0, the Option Base statement is never required.  However, if used, it  can appear only once in a module and must precede array declarations that include dimensions.

Tip   The To clause in the Dim, Private, Public, 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.

The Option Base statement only affects the lower bound of arrays in the module where the statement is located.


See Also

Dim Statement

LBound Function

Option Compare Statement

Option Explicit Statement

Private Statement

Public Statement

ReDim Statement

Static Statement


Option Compare Statement

See Also	Example

Used at module level to declare the default comparison method to use when string data is compared.

Syntax

Option Compare {Binary | Text }

Remarks

If used, the Option Compare statement must appear in a module before any statements that declare variables or define constants.

The Option Compare statement specifies the string comparison method (Binary or Text) for a module.  If a module doesn't include an Option Compare statement, the default text comparison method is Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters.  Sort order is determined by the code page. Option Compare Text results in string comparisons based on a case-insensitive text sort order determined by your system's locale.  The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)


See Also

Character Set

Comparison Operators

InStr Function

Option Base Statement

Option Explicit Statement

StrComp Function


Option Explicit Statement

See Also	Example

Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any statements that declare variables or define constants.

If you don't use the Option Explicit statement, all undeclared variables are of Variant type unless the default type is otherwise specified with a Deftype statement.

When you use the Option Explicit statement, you must explicitly declare all variables using the Dim, Private, Public, ReDim, or Static statements.  If you attempt to use an undeclared variable name, an error occurs at compile time.

Tip   Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid risking confusion in code where the scope of the variable is not clear.


See Also

Const Statement

Deftype Statements

Dim Statement

Function Statement

Option Base Statement

Option Compare Statement

Private Statement

Public Statement

ReDim Statement

Static Statement

Sub Statement


Option Private Statement

This statement is visible in the Visual Basic for applications object library, but is not available to Visual Basic, version 4.0.


Private Statement

See Also	Example

Used at module level to declare private variables and allocate storage space.

Syntax

Private varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] type]] . . .

The Private statement syntax has these parts:

Part	Description

varname	Name of the variable; follows standard variable naming conventions.

subscripts	Dimensions of an array variable; up to 60 multiple dimensions may be declared.  The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement.  The lower bound is zero if no Option Base statement is present.

New	Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object.  The New keyword can't be used to create variables of any intrinsic data type and can't be used to create dependent OLE Automation objects.

type	Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

Remarks

Private variables are available only to the module in which they are declared.

Use the Private statement to declare the data type of a variable.  For example, the following statement declares a variable as an Integer:

Private NumberOfEmployees As Integer

Also use a Private statement to declare the object type of a variable.  The following declares a variable for a new instance of a worksheet.

Private X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Private statement with empty parentheses to declare a dynamic array.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you do not specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip   When you use the Private statement in a procedure, it is a generally accepted programming practice to put the Private statement at the beginning of the procedure.


See Also

Array Function

Const Statement

Dim Statement

Function Statement

Option Base Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

ReDim Statement

Set Statement

Static Statement

Sub Statement

Type Statement


Property Get Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Property procedure, which gets the value of a property.

Syntax

[Public | Private][Static] Property Get name [(arglist)][As type]
[statements]
[name = expression]
[Exit Property]
[statements]
[name = expression]
End Property

The Property Get statement syntax has these parts:

Part	Description

Public	Indicates that the Property Get procedure is accessible to all other procedures in all modules.

Private	Indicates that the Property Get procedure is accessible only to other procedures in the module where it is declared.

Static	Indicates that the Property Get procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Property Get procedure, even if they are used in the procedure.

name	Name of the Property Get procedure; follows standard variable naming conventions, except that the name can be the same as a Property Let or Property Set procedure in the same module.

arglist	List of variables representing arguments that are passed to the Property Get procedure when it is called.  Multiple arguments are separated by commas.  The name and data type of each argument in a Property Get procedure must be the same as the corresponding arguments in a Property Let procedure (if one exists).

type	Data type of the value returned by the Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (except fixed length), Object, Variant, or user-defined type.  Arrays of any type can't be returned, but a Variant containing an array can.

The return type of a Property Get procedure must be the same data type as the last (or sometimes the only) argument in a corresponding Property Let procedure (if one exists) that defines the value assigned to the property on the right-hand side of an expression.

statements	Any group of statements to be executed within the body of the Property Get procedure.

expression	Value of the property returned by the procedure defined by the Property Get statement.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part	Description

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

varname	Name of the variable representing the argument; follows standard variable naming conventions.

type	Data type of the argument passed to the Property Get procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Property procedures are public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Property Get procedure inside another Property, Sub, or Function procedure.

The Exit Property keywords cause an immediate exit from a Property Get procedure.  Program execution continues with the statement following the statement that called the Property Get procedure.  Any number of Exit Property statements can appear anywhere in a Property Get procedure.

Like a Sub and Property Let procedure, a Property Get 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 or Property Let procedure, you can use a Property Get procedure on the right-hand side of an expression in the same way you use a Function or a property name when you want to return the value of a property.


See Also

Function Statement

Property Let Statement

Property Set Statement

Sub Statement


Property Let Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Property Let procedure, which assigns a value to a property.

Syntax

[Public | Private][Static] Property Let name [(arglist)]
[statements]
[Exit Property]
[statements]
End Property

The Property Let statement syntax has these parts:

Part	Description

Public	Indicates that the Property Let procedure is accessible to all other procedures in all modules.

Private	Indicates that the Property Let procedure is accessible only to other procedures in the module where it is declared.

Static	Indicates that the Property Let procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Property Let procedure, even if they are used in the procedure.

name	Name of the Property Let procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Set procedure in the same module.

arglist	List of variables representing arguments that are passed to the Property Let procedure when it is called.  Multiple arguments are separated by commas.  The name and data type of each argument in a Property Let procedure (except the last one) must be the same as the corresponding arguments in a Property Get procedure.  The last argument is the value assigned to the property on the right-hand side of an expression. The data type of the last (or sometimes the only) argument must be the same as the return type of the corresponding Property Get procedure.

statements	Any group of statements to be executed within the body of the Property Let procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part	Description

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

varname	Name of the variable representing the argument; follows standard variable naming conventions.

type	Data type of the argument passed to the Property Let procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Note   Every Property Let statement must define at least one argument for the procedure it defines.  That argument (or the last argument if there is more than one) contains the actual value to be assigned to the property when the procedure defined by the Property Let statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Property Let procedure inside another Property, Sub, or Function procedure.

The Exit Property keywords cause an immediate exit from a Property Let procedure.  Program execution continues with the statement following the statement that called the Property Let procedure.  Any number of Exit Property statements can appear anywhere in a Property Let procedure.

Like a Function and Property Get procedure, a Property Let 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 and Property Get procedure, both of which return a value, you can only use a Property Let procedure on the left-hand side of a property assignment expression or Let statement.


See Also

Function Statement

Let Statement

Property Get Statement

Property Set Statement

Sub Statement


Property Set Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Property procedure, which sets a reference to an object.

Syntax

[Public | Private][Static] Property Set name [(arglist)]
[statements]
[Exit Property]
[statements]
End Property

The Property Set statement syntax has these parts:

Part	Description

Public	Indicates that the Property Set procedure is accessible to all other procedures in all modules.

Private	Indicates that the Property Set procedure is accessible only to other procedures in the module where it is declared.

Static	Indicates that the Property Set procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Property Set procedure, even if they are used in the procedure.

name	Name of the Property Set procedure; follows standard variable naming conventions, except that the name can be the same as a Property Get or Property Let procedure in the same module.

arglist	List of variables representing arguments that are passed to the Property Set procedure when it is called.  Multiple arguments are separated by commas.  The last argument is the object reference used on the right-hand side of an object reference assignment.

statements	Any group of statements to be executed within the body of the Property procedure.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )][As type]

Part	Description

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

varname	Name of the variable representing the argument; follows standard variable naming conventions.

type	Data type of the argument passed to the Property Set procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Note   Every Property Set statement must define at least one argument for the procedure it defines.  That argument (or the last argument if there is more than one) contains the actual object reference for the property when the procedure defined by the Property Set statement is invoked.

Remarks

If not explicitly specified using either Public or Private, Property procedures are public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Property Set procedure inside another Property, Sub, or Function procedure.

The Exit Property keywords cause an immediate exit from a Property Set procedure.  Program execution continues with the statement following the statement that called the Property Set procedure.  Any number of Exit Property statements can appear anywhere in a Property Set procedure.

Like a Function and Property Get procedure, a Property Set 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 and Property Get procedure, both of which return a value, you can only use a Property Set procedure on the left-hand side of an object reference assignment (Set statement).


See Also

Function Statement

Property Get Statement

Property Let Statement

Set Statement

Sub Statement


Public Statement

See Also	Example

Used at module level to declare public variables and allocate storage space.

Syntax

Public varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] type]] . . .

The Public statement syntax has these parts:

Part	Description

varname	Name of the variable; follows standard variable naming conventions.

subscripts	Dimensions of an array variable; up to 60 multiple dimensions may be declared.  The argument subscripts uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement.  The lower bound is zero if no Option Base statement is present.

New	Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object.  The New keyword can't be used to create variables of any intrinsic data type and can't be used to create dependent OLE Automation objects.

type	Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

Remarks

Variables declared using the Public statement are available to all procedures in all modules in all applications.

Caution   The Public statement can't be used in a class module to declare a fixed-length string variable.

Use the Public statement to declare the data type of a variable.  For example, the following statement declares a variable as an Integer:

Public NumberOfEmployees As Integer

Also use a Public statement to declare the object type of a variable.  The following declares a variable for a new instance of a worksheet.

Public X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Public statement with empty parentheses to declare a dynamic array.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

If you do not specify a data type or object type and there is no Deftype statement in the module, the variable is Variant by default.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip   When you use the Public statement in a procedure, it is a generally accepted programming practice to put the Public statement at the beginning of the procedure.


See Also

Array Function

Const Statement

Dim Statement

Option Base Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

ReDim Statement

Set Statement

Static Statement

Type Statement


ReDim Statement

See Also	Example

Used at procedure level to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [As type][, varname(subscripts) [As type]] . . .

The ReDim statement syntax has these parts:

Part	Description

Preserve	Preserves the data in an existing array when you change the size of the last dimension.

varname	Name of the variable; follows standard variable naming conventions.

subscripts	Dimensions of an array variable; up to 60 multiple dimensions may be declared.  The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement.  The lower bound is zero if no Option Base statement is present.

type	Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.  For a Variant containing an array, type describes the type of each element of the array, but does not change the Variant to some other type.

Remarks

The ReDim statement is usually used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts).

You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.  However, you can't declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in a Variant.  If the array is contained in a Variant, the type of the elements can be changed using an As type clause.

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all.  For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension.  However, if your array has two or more dimensions you can change the size of only the last dimension and still preserve the contents of the array.  The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)

. . .

ReDim Preserve X(10, 10, 15)

Caution   If you make an array smaller than it was, data in the eliminated elements will be lost.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it were a separate variable.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Note   To resize an array contained in a Variant, you must explicitly declare the Variant variable before attempting to resize its array.


See Also

Array Function

Dim Statement

Option Base Statement

Private Statement

Public Statement

Set Statement

Static Statement


Rem Statement

Example

Used to include explanatory remarks in a program.

Syntax

Rem comment

You can also use the following syntax:

' comment

The comment argument is the text of any comment you want to include.  After the Rem keyword, a space before comment is required.

Remarks

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 the syntax examples, you can use a single quotation mark or apostrophe (') instead of the Rem keyword.  If the Rem keyword 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.


Set Statement

See Also	Example

Assigns an object reference to a variable or property.

Syntax

Set objectvar = {[New] objectexpression | Nothing}

The Set statement syntax has these parts:

Part	Description

objectvar	Name of the variable or property; follows standard variable naming conventions.

New	Keyword used to create a new instance of a Visual Basic object or an externally creatable OLE Automation object.  The New keyword can't be used to create new instances of any intrinsic data type and can't be used to create dependent OLE Automation objects.

objectexpression	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 of the same object type.

Nothing	Discontinues association of objectvar with any specific object.  Assigning objectvar to Nothing releases all the system and memory resources associated with the previously referenced object when no other variable refers to it.

Remarks

To be valid, objectvar must be an object type consistent with the object being assigned to it.

The Dim, Private, Public, ReDim, and Static statements only declare a variable that refers to an object.  No actual object is referred to until you use the Set statement to assign a specific object.

The following example illustrates how Dim is used to formally declare the variable MyDatabase as Database.  No instance of Database actually exists.  Set then assigns a reference to a new instance of Database to the MyDatabase variable.

Dim MyDatabase As Database

Set MyDatabase = New Database

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 keyword in the Set statement, you are actually creating an instance of the object.  The new instance is not loaded until the first reference is made to it or one of the object's members.


See Also

Dim Statement

Let Statement

Private Statement

Public Statement

ReDim Statement

Static Statement


Static Statement

See Also	Example

Used at procedure level to declare variables and allocate storage space.  Variables declared with the Static statement retain their value as long as the code is running.

Syntax

Static varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] type]] . . .

The Static statement syntax has these parts:

Part	Description

varname	Name of the variable; follows standard variable naming conventions.

subscripts	Dimensions of an array variable; up to 60 multiple dimensions may be declared.  The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement.  The lower bound is zero if no Option Base statement is present.

New	Keyword used to indicate that a declared object variable is a new instance of a Visual Basic object or an externally creatable OLE Automation object.  The New keyword can't be used to create variables of any intrinsic data type and can't be used to create dependent OLE Automation objects.

type	Data type of the variable; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

Remarks

Once module code is running, variables declared with the Static statement retain their value until the module is reset or restarted.  Use the Static statement in nonstatic procedures to explicitly 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 to declare the object type of a variable.  The following declares a variable for a new instance of a worksheet:

Static X As New Worksheet

If the New keyword is not used when declaring an object variable, no instance of the object actually exists.  A variable that refers to an object must be assigned an existing object using the Set statement before it can be used.  Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

If you do not specify a data type or object type, and there is no Deftype statement in the module, the variable is Variant by default.

Note   The Static statement and the Static keyword affect the lifetime of variables differently.  If you declare a procedure using the Static keyword (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 for as long as the program is running.

When variables are initialized, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string, and a fixed-length string is filled with zeros.  Variant variables are initialized to Empty.  Each element of a user-defined type variable is initialized as if it were a separate variable.

Tip   When you use the Static statement in a procedure, it is a generally accepted programming practice to put the Static statement at the beginning of the procedure with any Dim statements.


See Also

Array Function

Dim Statement

Function Statement

Option Base Statement

Private Statement

Public Statement

ReDim Statement

Sub Statement


Sub Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Private | Public] [Static] Sub name [(arglist)]
[statements]
[Exit Sub]
[statements]
End Sub

The Sub statement syntax has these parts:

Part	Description

Public	Indicates that the Sub procedure is accessible to all other procedures in all modules.

Private	Indicates that the Sub procedure is accessible only to other procedures in the module where it is declared.

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, even if they are used in the procedure.

name	Name of the Sub; follows standard variable naming conventions.

arglist	List of variables representing arguments that are passed to the Sub procedure when it is called.  Multiple variables are separated by commas.

statements	Any group of statements to be executed within the body of the Sub procedure.

The arglist argument has the following syntax and parts:

[Optional][ByVal | ByRef][ParamArray] varname[( )] [As type]

Part	Description

Optional	Indicates that an argument is not required.  If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword.  All Optional arguments must be Variant.  Optional can't be used for any argument if ParamArray is used.

ByVal	Indicates that the argument is passed by value.

ByRef	Indicates that the argument is passed by reference.

ParamArray	Used only as the last argument in arglist to indicate that the final argument is an Optional array of Variant elements.  The ParamArray keyword allows you to provide an arbitrary number of arguments.  It may not be used with ByVal, ByRef, or Optional.

varname	Name of the variable representing the argument; follows standard variable naming conventions.

type	Data type of the argument passed to the procedure; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String (variable length only), Object, Variant, a user-defined type, or an object type.

Remarks

If not explicitly specified using either Public or Private, Sub procedures are public by default.  If Static is not used, the value of local variables is not preserved between calls.

All executable code must be in procedures.  You can't define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keywords cause an immediate exit from a Sub procedure.  Program execution continues with the statement following the statement that called the Sub procedure.  Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, 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 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 keyword 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.  Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution   A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you have defined at the module level has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name.  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

Option Explicit Statement

Property Get Statement

Property Let Statement

Property Set Statement

Static Statement


Type Statement

See Also	Example

Used at module level to define a user-defined data type containing one or more elements.

Syntax

[Private | Public] Type varname
  elementname [([subscripts])] As type
[ elementname [([subscripts])] As type]
. . .
End Type

The Type statement syntax has these parts:

Part	Description

Public	Used to declare user-defined types that are available to all procedures in all modules in all projects.

Private	Used to declare user-defined types that are available only within the module where the declaration is made.

varname	Name of the user-defined type; follows standard variable naming conventions.

elementname	Name of an element of the user-defined type.  Element names also follow standard variable naming conventions, except that keywords can be used.

subscripts	Dimensions of an array element.  Use only parentheses when declaring an array whose size can change.  The subscripts argument uses the following syntax:

[lower To] upper [,[lower To] upper] . . .

When not explicitly stated in lower, the lower bound of an array is controlled by the Option Base statement.  The lower bound is zero if no Option Base statement is present.

type	Data type of the element; may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, String * length (for fixed-length strings), Object, Variant, another user-defined type, or an object type.

Remarks

The Type statement can be used only at module level.  Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere within the scope of the declaration.  Use Dim, Private, Public, ReDim, or Static to declare a variable of a user-defined type.

In standard modules, user-defined types are public by default.  This visibility can be changed using the Private keyword.  In class modules, however, user-defined types can only be private and the visibility cannot be changed using the Public keyword.

Line numbers and line labels aren't allowed in Type...End Type blocks.

User-defined types are often used with data records, which frequently consist of a number of related elements of different data types.

The following example shows the use of fixed-size 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 fixed-size array within a user-defined type, its dimensions must be declared with numeric literals or constants rather than variables.

The setting of the Option Base statement determines the lower bound for arrays within user-defined types.


See Also

Data Type Summary

Dim Statement

Option Base Statement

Private Statement

Public Statement

ReDim Statement

Static Statement


UBound Function

See Also	Example

Returns the largest available subscript for the indicated dimension of an array.

Syntax

UBound(arrayname[, dimension])

The UBound function syntax has these parts:

Part	Description

arrayname	Name of the array variable; follows standard variable naming conventions.

dimension	Whole number indicating which dimension's upper bound is returned.  Use 1 for the first dimension, 2 for the second, and so on.  If dimension is omitted, 1 is assumed.

Remarks

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

UBound returns the 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

Public Statement

LBound Function

Option Base Statement

ReDim Statement

Static Statement


Conversion Functions

Asc Function

CBool Function

CByte Function

CCur Function

CDate Function

CDbl Function

Chr Function

CInt Function

CLng Function

CSng Function

CStr Function

CVar Function

CVErr Function

Format Function

Hex Function

Oct Function

Str Function

Val Function


Asc Function

See Also	Example

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

Syntax

Asc(string)

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

Note   Another function (AscB) is provided for use with byte data contained in a string.  Instead of returning the character code for the first character, AscB returns the first byte.


See Also

Character Set

Chr Function

Conversion Functions


CBool Function

See Also	Example

Converts an expression to a Boolean.

Syntax

CBool(expression)

The expression argument is any valid numeric or string expression.

Remarks

If expression is zero, False is returned; otherwise, True is returned.  If expression can't be interpreted as a numeric value, a run-time error occurs.


See Also

Conversion Functions

Data Type Summary


CByte Function

See Also	Example

Converts an expression to a Byte.

Syntax

CByte(expression)

The expression argument is any valid numeric or string expression.

Remarks

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

You should use the CByte function instead of Val to provide internationally-aware conversions from any other data type to a Byte.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Byte data type, an error occurs.


See Also

Conversion Functions

Data Type Summary


CCur Function

See Also	Example

Converts an expression to a Currency.

Syntax

CCur(expression)

The expression argument is any valid numeric or string expression.

Remarks

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

You should use the CCur function instead of Val to provide internationally-aware conversions from any other data type to a Currency.  For example, different decimal separators are properly recognized depending on the locale setting of your computer, as are different thousand separators and various currency options.

If expression lies outside the acceptable range for the Currency data type, an error occurs.


See Also

Conversion Functions

Data Type Summary


CDate Function

See Also	Example

Converts an expression to a Date.

Syntax

CDate(date)

The date argument is any valid date expression.

Remarks

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

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

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


See Also

Conversion Functions

Data Type Summary

IsDate Function

DateSerial Function


CDbl Function

See Also	Example

Converts an expression to a Double.

Syntax

CDbl(expression)

The expression argument is any valid numeric or string expression.

Remarks

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

You should use the CDbl function instead of Val to provide internationally aware conversions from any other data type to a Double.  For example, different decimal separators and thousands separators are properly recognized depending on the locale setting of your system.


See Also

Conversion Functions

Data Type Summary


CInt Function

See Also	Example

Converts an expression to an Integer.

Syntax

CInt(expression)

The expression argument is any valid numeric or string expression.

Remarks

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

You should use the CInt function instead of Val to provide internationally-aware conversions from any other data type to an Integer.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Integer data type, an error occurs.

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

Conversion Functions

Data Type Summary

Fix Function

Int Function


CLng Function

See Also	Example

Converts an expression to a Long.

Syntax

CLng(expression)

The expression argument is any valid numeric or string expression.

Remarks

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

You should use the CLng function instead of Val to provide internationally-aware conversions from any other data type to a Long.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Long data type, an error occurs.

Note   CLng 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 CLng function always rounds it to the nearest even number.  For example, 0.5 rounds to 0, and 1.5 rounds to 2.


See Also

Conversion Functions

Data Type Summary

Fix Function

Int Function


CSng Function

See Also	Example

Converts an expression to a Single.

Syntax

CSng(expression)

The expression argument is any valid numeric or string expression.

Remarks

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

You should use the CSng function instead of Val to provide internationally-aware conversions from any other data type to a Single.  For example, different decimal separators are properly recognized depending on the locale setting of your system, as are different thousand separators.

If expression lies outside the acceptable range for the Single data type, an error occurs.


See Also

Conversion Functions

Data Type Summary


CStr Function

See Also	Example

Converts an expression to a String.

Syntax

CStr(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CStr to force the result to be expressed as a String.

You should use the CStr function instead of Str to provide internationally-aware conversions from any other data type to a String.  For example, different decimal separators are properly recognized depending on the locale setting of your system.

The data in expression determines what is returned according to the following table:

If expression is	CStr returns

Boolean	A String containing True or False.

Date	A String containing a date in the short-date format of your system.

Null	A run-time error.

Empty	A zero-length String ("").

Error	A String containing the word Error followed by the error number.

Other numeric	A String containing the number.


See Also

Conversion Functions

Data Type Summary

Str Function


CVar Function

See Also	Example

Converts an expression to a Variant.

Syntax

CVar(expression)

The expression argument is any valid numeric or string expression.

Remarks

In general, you can document your code using the data type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type.  For example, use CVar to force the result to be expressed as a Variant.


See Also

Conversion Functions

Data Type Summary


CVErr Function

See Also	Example

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

Syntax

CVErr(errornumber)

The errornumber argument is any valid error number.

Remarks

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

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


See Also

Conversion Functions

Data Type Summary

IsError Function


Val Function

See Also	Example

Returns the numbers contained in a string.

Syntax

Val(string)

The string argument is any valid string expression.

Remarks

The Val function stops reading the string at the first character it can't recognize as part of a number.  Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized.  However, the function recognizes radix prefixes &O (for octal) and &H (for hexadecimal).  Blanks, tabs, and linefeeds are stripped from the argument.

The following returns the value 1615198:

Val("    1615 198th Street N.E.")

In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")

Note   The Val function recognizes only the period (.) as a valid decimal separator.  When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CDbl instead to convert a string to a number.


See Also

CDbl Function

Str Function


Creating an Object Variable

See Also

You can treat an object variable exactly the same as the object to which it refers.  You can set or return the properties of the object or use any of its methods.

To create an object variable

1.	Declare the object variable.

2.	Assign the object variable to an object.

Declaring an object variable

Use the Dim statement or one of the other declaration statements (Public, Private, or Static) to declare an object variable.  A variable that refers to an object must be a Variant, an Object, or a specific type of object.  For example, the following declarations are valid:

Dim MyObject	' Declares MyObject as Variant data type.

Dim MyObject As Object	' Declares MyObject as Object data type.

Dim MyObject As Font	' Declares MyObject as Font type.

Note   As with other variables, if you use an object variable without declaring it first, the data type of the object variable is Variant by default.

The Object data type allows you to create a generic reference to any object.  You can declare an object variable with the Object data type in situations where the specific object type is not known until the procedure runs.

If you know the specific object type an object variable will refer to, you should declare the object variable as that object type.  For example, if the application you use contains a Sample object type, you can declare an object variable for that object using either of these statements:

Dim MyObject As Object	' Declared as generic object.

Dim MyObject As Sample	' Declared only as Sample object.

Declaring specific object types provides automatic type checking, faster code, and improved readability.

Assigning an object variable to an object

Use the Set statement to assign an object to an object variable.  You can assign an object expression or Nothing.  For example, the following object variable assignments are valid:

Set MyObject = YourObject	' Assign object reference.

Set MyObject = Nothing	' Discontinue association.

Setting an object variable equal to Nothing discontinues the association of the object variable with any specific object.  This prevents you from accidentally changing the object by changing the variable.  An object variable is always set to Nothing after closing the object with which it is associated so you can easily test whether or not the object variable points to a valid object.  For example:

If Not MyObject Is Nothing Then	' Variable refers to valid object.

. . .

End If

Referring to the current instance of an object

Use the Me keyword to refer to the current instance of the object where the code is currently running.  All procedures associated with the current object have access to the object referred to as Me.  Using Me is particularly useful for passing information about the current instance of an object to a procedure in another module.  For example, suppose you have the following procedure in a module:

Sub ChangeObjectColor(MyObjectName As Object)

MyObjectName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)

End Sub

You can call the procedure and pass the current instance of the object as an argument using the following statement:

ChangeObjectColor Me


 See Also

CreateObject Function

GetObject Function

Me

Nothing

Object Data Type

Set Statement


Creating Arrays

See Also

Unless you specify a data type, declared arrays contain variants.  Arrays of type Variant consume 16 bytes for each element that the array contains.  The following lines of code compare the size of several arrays:

' Integer array uses 22 bytes (11 elements * 2 bytes).

ReDim MyIntegerArray(10) As Integer

' Double-precision array uses 88 bytes (11 elements * 8 bytes).

ReDim MyDoubleArray(10) As Double

' Variant array uses at least 176 bytes (11 elements * 16 bytes).

ReDim MyVariantArray(10)

' Integer array uses 100 * 100 * 2 bytes (20,000 bytes).

ReDim MyIntegerArray (99, 99) As Integer

' Double-precision array uses 100 * 100 * 8 bytes (80,000 bytes).

ReDim MyDoubleArray (99, 99) As Double

' Variant array uses at least 160,000 bytes (100 * 100 * 16 bytes).

ReDim MyVariantArray(99, 99)

The maximum size of an array varies, based on your operating system and how much memory is available.  You aren't likely to encounter this limit, but using arrays that exceed the amount of random-access memory available on your system are slower because the data must be read from and written to disk.


See Also

Array Function

Dim Statement

Private Statement

Public Statement

ReDim Statement

Static Statement

Using Data Types Efficiently


Creating Recursive Procedures

See Also

Procedures have a limited amount of space for variables.  Each time a procedure calls itself, more of that space is used.  This type of procedure is called a recursive procedure.  A recursive procedure that indefinitely calls itself eventually causes an error.  For example:

Function RunOut(Maximum)

RunOut = RunOut(Maximum)	' Error Calls itself without ever exiting.

End Function

This error may be less obvious when two procedures call each other indefinitely, or some condition that limits the recursion is never met.  Recursion has its uses.  For example, the following procedure uses a recursive function to calculate factorials:

Function Factorial (N)

If N <= 1 Then	' Reached end of recursive calls.

Factorial = 1	' (N = 0) so climb back out of calls.

Else	' Call Factorial again if N > 0.

Factorial = Factorial(N - 1) * N

End If

End Function

You should test your recursive procedure to make sure it does not call itself so many times that you run out of memory.  If you get an error, make sure your procedure is not calling itself indefinitely.  After that, try to conserve memory by:

Eliminating unneeded variables.

Using data types other than Variant.

Reevaluating the logic of the procedure.  Often you can substitute nested loops for recursion.


See Also

Making Faster For...Next Loops

Using Data Types Efficiently


Making Faster For...Next Loops

See Also

Integers are not only smaller than the Variant data type, they are also slightly faster to update.  Since computers operate at very great speed, this difference is only noticeable if you perform many thousands of operations.  For example:

Dim CountFaster As Integer	' First case, use Integer.

For CountFaster = 0 to 32766

Next CountFaster

Dim CountSlower As Variant	' Second case, use Variant.

For CountSlower = 0 to 32766

Next CountSlower

The first case above takes slightly less time to execute than the second case.  However, if CountFaster exceeds 32,767, an error occurs.  To fix this, you could change CountFaster to the Long data type, which accepts a much wider range of integers.  However, variables of the data type Long are slower to update than variables of type Integer.  In general, the smaller the data type, the less time it takes to update.  Variants are slightly slower than their equivalent data type.


 See Also

Data Type Summary

Using Data Types Efficiently


Module Scope

See Also

Variables and objects defined at module level are visible in all procedures within the module.  You must qualify them with their module name to distinguish them from procedure-level variables with the same name.  For example, the variable MyVar declared at module level of MyModule can be distinguished from a variable MyVar declared in a procedure by qualifying it as MyModule.MyVar.  However, you need not qualify a module-level variable name in a procedure that has no local variable of the same name.  Except in Class modules, module-level variables are always Static, that is, they exist whenever their module is part of a running program.

Procedure names are always defined at module level, and by default are visible (callable) from anywhere in a project.  When the same procedure name is used in more than one module. you must qualify the procedure name with the module name to unambiguously identify the procedure you want to invoke.  For example, MyModule.MyProc uniquely identifies a procedure named MyProc in MyModule

If you want a procedure to be visible only within its own module, you can define it as Private to prevent its being called from procedures in other modules in a project. The lifetime of a procedure is similar to that of a Static variable, whenever its module is part of a running program.

Variables and symbolic constants (declared with the Const statement) are Private by default.  Procedures are Public by default.  Structure types (declared with the Type statement) are Public by default.


See Also

Const Statement

Private

Procedure Scope

Public

Scope and Visibility

Static

Type Statement


Naming-Conflict Errors

See Also

A naming-conflict bug can occur even if you use Option Explicit, which normally protects you from such situations.  For example, if you use an undeclared identifier in a For...Next loop in a procedure, and that variable has the same name as one with wider scope, you can inadvertently change the variable with wider scope:

Option Explicit	' Forces declaration before use of variables.

Dim X	' Module-level declaration of X.

Sub AnyProc()

' A Dim X statement here would prevent a bug.

For X = 0 to 25	' Loop counter not declared in its procedure.

Print X	' This X is the same as the module-level X.

Next X

Call AnotherProc

End Sub

Sub AnotherProc()

X = X + 1

Print X	' This X has value of loop counter in AnyProc.

End Sub


See Also

For...Next Statement

Option Explicit Statement

Resolving Naming Conflicts

Scope and Visibility


OLE Automation

See Also

OLE Automation is an industry-standard technology that applications use to expose their OLE objects to development tools, macro languages, and other applications 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, document, paragraph, sentence, bookmark, or selection.

When an application supports OLE Automation, the objects it exposes can be accessed by Visual Basic.  Use Visual Basic to manipulate these objects by invoking methods on the object or by getting and setting the object's properties.  For example, if you created an OLE Automation object named MyObj, you could write this code to manipulate the object:

MyObj.Insert "Hello, world."	' Place text.

MyObj.Bold = True	' Format text.

MyObj.SaveAs  "C:\WORDPROC\DOCS\TESTOBJ.DOC"	' Save the object.

The following functions let you access an OLE Automation object:

Function	Description

CreateObject	Creates a new object of a specified type.

GetObject 	Retrieves an object from a file.

The objects, functions, properties and methods supported by an application are usually defined in the application's object library.


 See Also

CreateObject Function

GetObject Function

Set Statement


Passing Arguments Efficiently

See Also

All arguments are passed to procedures by reference unless you specify otherwise.  This is efficient because all arguments take the same amount of time to pass and the same amount of space (4 bytes) within a procedure regardless of the argument's data type.

You can pass an argument by value, instead of by reference, if you include the ByVal keyword in the procedure's declaration.  Arguments passed by value consume from 2 to 16 bytes within the procedure, depending on the argument's data type.  Larger data types take slightly longer to pass than smaller ones. Because of this, String and Variant data types generally should not be passed by value.

Passing an argument by value copies the original variable.  Changes to the argument within the procedure aren't reflected back to the original variable.  For example:

Function Factorial (ByVal MyVar As Integer)	' Function declaration.

MyVar = MyVar - 1

If MyVar = 0 Then

Factorial = 1

Exit Function

End If

Factorial = Factorial(MyVar) * (MyVar + 1)

End Function

' Call Factorial with a variable S.

S = 5

Print Factorial(S)	' Displays 120 (the factorial of 5).

Print S	' Displays 5.

Without ByVal in the function declaration, the Print statements above would display 1 and 0.  This is because MyVar would then refer to variable S, which is reduced by 1 until it equals 0.

Because ByVal makes a copy of the argument, it allows you to pass a variant to the Factorial function above.  You can't pass a variant by reference if the procedure that declares the argument is another data type.

In general, arguments passed using ByVal are faster to reference while arguments passed using ByRef are faster to pass.


See Also

ByRef

ByVal

Data Types Summary

Using Data Types Efficiently


Procedure Scope

See Also

Variables and objects defined at procedure level (within procedures) are private to the procedure in which they are defined and are never visible outside the procedure.  If declared Static, the variable exists whenever its module is a part of the running program; otherwise, local variables are created each time the procedure begins, and are destroyed each time the procedure ends.

Procedures can't be nested within other procedures.


See Also

Module Scope

Scope and Visibility

Static


Resolving Naming Conflicts

See Also

A naming conflict occurs when you try to create or use an identifier that is recognized by Visual Basic as having been previously defined.  In some cases, naming conflicts generate errors such as Ambiguous name detected or Duplicate declaration in current scope.  Naming conflicts may not be detected and can result in bugs in your code that produce erroneous results, especially if you do not explicitly declare all variables before first use.

Most naming conflicts can be resolved by understanding the scoping characteristics of identifiers for data, objects, and procedures.  Visual Basic has two scoping levels: procedure level and module level.

A naming conflict can occur when an identifier:

Is visible at more than one scoping level

Has two different meanings at the same level

For example, procedures in separate modules can have the same name.  Therefore, a procedure named MySub can be defined in modules named Mod1 and Mod2.  No conflicts occur if the procedures are called only from their own modules.  However, an error can occur if MySub is called from a third module, and no qualification is provided to distinguish between the two MySub procedures.  For example, to call the MySub (defined in both Mod1 and Mod2 modules) from Mod5, simply specify it as Mod1.MySub or Mod2.MySub in the call.

Visual Basic matches each reference to an identifier with the "closest" declaration of a matching identifier.  For example, if MyID is declared Public in two modules in a project (Mod1 and Mod2), you can specify the MyID declared in Mod2 without qualification from within Mod2, but you must qualify it (as Mod2.MyID) to specify it in Mod1.

Most naming conflicts can be resolved by preceding the name with a qualifier that consists of its module name.  For example:

YourModule.YourSub MyProject.MyModule.MyVar

The preceding code calls the Sub procedure YourSub and passes MyVar as an argument.  You can use any combination of qualifiers that is sufficient to differentiate identical identifiers.

Typical errors caused by naming conflicts include those for ambiguous names, duplicate declarations, undeclared identifiers, procedure not found, and so on.


See Also

Naming-Conflict Errors

Option Explicit Statement

Public

Scope and Visibility

Sub Statement


Returning Strings from Functions

See Also

Some functions have two versions, one that returns a Variant data type and one that returns a String data type.  The variant versions tend to be the most convenient because variants handle conversions between different types of data automatically.

Consider using the String type version when:

Your program is very large and uses many variables.

You want to detect when data of one type is converted to another type.

You write data directly to random-access files.

The following functions return values in a String type variable when you append a dollar sign ($) to the function name.  These functions have the same usage and syntax as their variant equivalents without the dollar sign.

Chr$	ChrB$	CurDir$	Date$
Dir$	Error$	Format$	Hex$
Input$	InputB$	LCase$	Left$
LeftB$	Mid$	MidB$	Oct$
Right$	RightB$	RTrim$	Space$
Str$	String$	Time$	Trim$
UCase$


See Also

Data Type Summary

Saving Space with Data Types

Writing Data to Files


Saving Space with Data Types

See Also

The Byte data type (8 bits) takes the least amount of space in your computer's memory.  It is not necessarily the most efficient data type to use when trying to save space, however, because for many computers, the smallest data storage unit is a 2-byte data word.  Since two bytes are stored even if you're using just a single byte for your data, there is no savings in memory.  However, a significant memory savings can occur when you have an array of type Byte.  Since the elements of an array are stored contiguously, an array of Bytes is stored in data words two elements at a time, realizing a memory savings of almost 50 percent.

In most cases, Integer is the most efficient data type to use when you're trying to save space.  Except as noted above, the Integer takes the least amount of space in your computer's memory.  For example, you can fit eight integers (8 * 2 bytes) in the space used by one Variant (16 bytes).  However, in most cases, using data types to save memory space is of limited value.  In general, you should not encounter memory storage limits unless your code contains, or you inadvertently create, enormous arrays or recursive procedures.


See Also

Creating Arrays

Creating Recursive Procedures

Data Type Summary

Using Data Types Efficiently


Scope and Visibility

See Also

Visual Basic has two levels of scope and two levels of visibility that determine where and when an identifier is recognized (visible), as illustrated in the following table:

Scoping Level	Private	Public
Procedure-level	All identifiers are Private and can't be changed.	Not applicable.
Module-level	Identifiers are Private to the module in which they appear.	Identifiers are available to all modules in a project.
Visual Basic uses a number of different keywords to declare the identifiers it recognizes.  The following table shows the Visual Basic keywords, what they're used to declare, the default visibility and an example of usage:

Keyword	Used to Declare	Default Visibility	Usage Example
Const	Constants	Private	Const Pi = 3.1415
Dim	Variables	Private	Dim A As Variant
Sub	Sub procedure	Public	Sub MyProc(A As Integer) ... End Sub
Function	Function procedure	Public	Function Sqrt(A) As Double ... End Function
Property	Property procedures	Public	Property Get PCol() As String ... End Property
Type	User-defined types	Public	Type EmployeeRecord    ID As Integer    Name As String End Type
The Private keyword can be used as a modifier with any of the keywords (except Dim) to override Public default visibility.  Similarly, the Public keyword can be used as a modifier with any of the keywords (except Dim) to override Private visibility.

The Dim statement is used only to declare module-level variables that are Private to a module.  However, there are two other statements you can use to explicitly declare the visibility of module-level variables you are declaring.  Use the Private statement to declare module-level variables that are available only to the procedures in the module in which they are declared.  Use the Public statement to declare variables that are universally available to other procedures outside the module where they reside.

Variables and symbolic constants (declared with the Const statement) are Private by default. User-defined types (declared with the Type statement) and procedures are Public by default.


See Also

Const Statement

Module Scope

Private

Procedure Scope

Public

Resolving Naming Conflicts

Static

Type Statement


Using Data Types Efficiently

See Also

Unless otherwise specified, undeclared variables are assigned the Variant data type.  This data type makes it easy to write programs, but it is not always the most efficient data type to use.

You should consider using other data types if:

Your program is very large and uses many variables.

Your program needs to run as quickly as possible.

You want to detect when data of one type must be converted to another type.

You write data directly to random-access files.

In addition to the Variant type, supported data types include Byte, Boolean, Integer, Long, Single, Double, Currency, Date, Object, and String.  Use the Dim statement to declare a variable of a specific type, for example:

Dim X As Integer

This statement declares that a variable X that is an integer [image] a whole number between -32,768 and 32,767.  If you try to set X to a number outside that range, an error occurs.  If you try to set X to a fraction, the number is rounded.  For example:

X = 32768	' Causes error

X = 5.9	' Sets x to 6.


See Also

Data Type Summary

Making Faster For...Next Loops

Saving Space with Data Types

Writing Data to Files


Working Across Applications

See Also

Visual Basic can create new objects and retrieve existing objects from these Microsoft applications:

Application	Object type	Class
Microsoft Access version 7.0	Application	Access Application
Microsoft Excel version 5.0	Application	Excel.Application
	Worksheet	Excel.Sheet
	Chart	Excel.Chart
Microsoft Project version 4.0	Application	MSProject.Project
Microsoft Word version 6.0	WordBasic	Word.Basic
Note that in later versions you may be able to create and retrieve additional objects from other applications using Visual Basic.  Other applications may also provide objects that you can create using Visual Basic.  See your application's documentation for more information.

To create an new object or get an existing object from another application, use the CreateObject or GetObject functions:

' Start Microsoft Excel and create a new Worksheet object.

Set ExcelWorksheet = CreateObject("Excel.Sheet")

' Start Microsoft Excel and open an existing Worksheet object.

Set ExcelWorksheet = GetObject("SHEET1.XLS")

' Start Microsoft Word.

Set WordBasic = CreateObject("Word.Basic")

Different applications behave in different ways when started with CreateObject or GetObject.  For example, Microsoft Excel starts up invisibly; Microsoft Word starts up visibly.  While Microsoft Excel is invisible, it is not displayed on the screen or in the Windows Task List.  To display Microsoft Excel and add it to the Task List, set its Visible property to True.  For example:

ExcelWorksheet.Application.Visible = True

Setting Microsoft Excel's Visible property to False makes the application invisible and removes it from the Task List.  Microsoft Excel does not close, however, and is still available to Visual Basic.

Microsoft Word closes when its object variable is set to Nothing or goes out of scope.  If you don't save changes before this happens, edits will be lost.  For example:

' Save changes and close Word.

WordBasic.FileSaveAll

Set WordBasic = Nothing

Microsoft Excel closes if it is invisible when its object variable is set to Nothing or goes out of scope.

' If Microsoft Excel is invisible it will close. If not, it stays open.

Set ExcelWorksheet = Nothing

Most applications also provide an Exit or Quit method that closes the application whether or not it is visible.  For more information on the objects, methods, and properties an application provides, see the application's documentation.

Some applications allow you to use the New keyword to create an object of any class that exists in its type library.  For example:

Dim X As New Field

In this case, Field is an example of a class in the data access type library.  A new instance of a Field object is created using this syntax.  Refer to your application's documentation for information about which object classes can be created in this way.


See Also

CreateObject Function

GetObject Function

New

Nothing

Set Statement


Writing Data to Files

See Also

When working with large amounts of data, it is often convenient to write data to or read data from a file.  The Open statement lets you create and access files directly.  Open provides three types of file access:

Sequential access (Input, Output, and Append modes), commonly used for writing text files, such as error logs and reports.

Random access (Random mode), used whenever you need to read and write data to a file without closing it.  Random access files keep data in records, which makes it easy to locate information quickly.

Binary access (Binary mode), used in some specialized cases where you need to read or write to any byte position in a file, such as when storing or displaying a bitmap image.

The following table shows the statements typically used when writing data to and reading data from files.

Access Type	Writing Data	Reading Data

Sequential	Print #, Write #	Input #

Random	Put	Get

Binary	Put	Get


See Also

Data Type Summary

Get Statement

Input # Statement

Open Statement

Print # Statement

Put Statement

Write # Statement


Call Statement

See Also	Example

Transfers control to a Sub procedure, Function procedure, dynamic-link library (DLL) procedure.

Syntax

[Call] name [argumentlist]

The Call statement syntax has these parts:

Part	Description

Call	Optional keyword; if specified, you must enclose argumentlist in parentheses.  For example:

Call MyProc(0)

name	Name of the procedure to call.

argumentlist	Comma-delimited list of variables, arrays, or expressions to pass to the procedure.  Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are to be treated by the called procedure.  However, ByVal and ByRef can be used with Call only when making a call to a DLL procedure.

Remarks

You are not required to use the Call keyword when calling a procedure.  However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses.  If you omit the Call keyword, you also must omit the parentheses around argumentlist.  If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.


See Also

Declare Statement


DoEvents Function

See Also	Example

Yields execution so that the operating system can process other events.

Syntax

DoEvents( )

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

The DoEvents function returns the number of open forms.

DoEvents passes control to the operating system.  Control is not returned until the operating system has finished processing the events in its queue and  all keys in the SendKeys queue have been sent.

If parts of your code take up a lot of processor time, use DoEvents periodically to relinquish control to the operating system so that events, such as keyboard input and mouse clicks, can be processed without significant delay.

Caution   Make sure the procedure that has given up control with DoEvents is not executed again from a different part of your code 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.


See Also

Idle Method

Make OLE DLL File Command

SendKeys Statement


Do...Loop Statement

See Also	Example

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop

Or, you can use this equally valid syntax:

Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]

The Do...Loop statement syntax has these parts:

Part	Description

condition	Numeric or string expression that is True or False.  If condition is Null, condition is treated as False.

statements	One or more statements that are repeated while or until condition is True.

Remarks

The Exit Do can only be 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.

When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.


See Also

Exit Statement

For...Next Statement

While...Wend Statement


End Statement

See Also	Example

Ends a procedure or block.

Syntax

End

End Function

End If

End Property

End Select

End Sub

End Type

End With

The End statement syntax has these forms:

Statement	Description

End	Terminates execution.  Never required by itself but may be placed anywhere in a procedure to close files opened with the Open statement and to clear variables.

End Function	Required to end a Function statement.

End If	Required to end a block If...Then...Else statement.

End Property	Required to end a Property Let, Property Get, or Property Set procedure.

End Select	Required to end a Select Case statement.

End Sub	Required to end a Sub statement.

End Type	Required to end a user-defined type definition (Type statement).

End With	Required to end a With statement.

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

When executed, the End statement resets all module-level variables and all static local variables in all modules.  If you need to preserve the value of these variables, use the Stop Statement instead.  You can then resume execution while preserving the value of those variables.


See Also

Exit Statement

Function Statement

If...Then...Else Statement

Make OLE DLL File Command

Property Get Statement

Property Let Statement

Property Set Statement

Select Case Statement

Stop Statement

Sub Statement

Type Statement

With Statement


Exit Statement

See Also	Example

Exits a block of Do...Loop, For...Next, Function, Sub, or Property code.

Syntax

Exit Do

Exit For

Exit Function

Exit Property

Exit Sub

The Exit statement syntax has these forms:

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 where it occurs.

Exit For	Provides a way to exit a For loop.  It can be used only in a For...Next or For Each...Next loop.  Exit For transfers control to the statement following the Next statement.  When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where it occurs.

Exit Function	Immediately exits the Function procedure in which it appears.  Execution continues with the statement following the statement that called the Function.

Exit Property	Immediately exits the Property procedure in which it appears.  Execution continues with the statement following the statement that called the Property procedure.

Exit Sub	Immediately exits the Sub procedure in which it appears.  Execution continues with the statement following the statement that called the Sub.

Remarks

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

For Each...Next Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Stop Statement

Sub Statement


For Each...Next Statement

See Also	Example

Repeats a group of statements for each element in an array or collection.

Syntax

For Each element In group
[statements]
[Exit For]
[statements]
Next [element]

The For Each...Next statement syntax has these parts:

Part	Description

element	Variable used to iterate through the elements of the collection or array.  For collections, element can only be a Variant variable, a generic Object variable, or any specific OLE Automation object variable.  For arrays, element can only be a Variant variable.

group	Name of an object collection or array (except an array of user-defined types).

statements	One or more statements that are executed on each item in group.

Remarks

The For Each block is entered if there is at least one element in group.  Once the loop has been entered, all the statements in the loop are executed for the first element in group.  Then, as long as there are more elements in group, the statements in the loop continue to execute for each element.  When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit.  Any number of Exit For statements may be placed anywhere in the loop.  The Exit For is often used with the evaluation of some condition (for example, If...Then),  and transfers control to the statement immediately following Next.

You can nest For Each...Next loops by placing one For Each...Next loop within another.  However, each loop element must be unique.

Note   If you omit element in a Next statement, execution continues as if you had included it.  If a Next statement is encountered before its corresponding For statement, an error occurs.

You can't use the For Each...Next statement with an array of user-defined types because a Variant can't contain a user-defined type.


See Also

Data Type Summary

Do...Loop Statement

Exit Statement

For...Next Statement

While...Wend Statement


For...Next Statement

See Also	Example

Repeats a group of statements a specified number of times.

Syntax

For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]

The For...Next statement syntax has these parts:

Part	Description

counter	Numeric variable used as a loop counter.  The variable can't be an element of a user-defined type.

start	Initial value of counter.

end	Final value of counter.

step	Amount counter is changed each time through the loop.  If not specified, step defaults to one.

statements	One or more statements between For and Next that are executed the specified number of times.

Remarks

The step argument can be either positive or negative.  The value of the step argument determines loop processing as follows:

Value	Loop executes if

Positive or 0	counter <= end

Negative	counter >= end

Once the loop starts and all statements in the loop have executed, step is added to counter.  At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Tip   Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

The Exit For can only be used within a For Each...Next or For...Next control structure to provide an alternate way to exit.  Any number of Exit For statements may be placed anywhere in the loop.  The Exit For is often used with the evaluation of some condition (for example, If...Then), and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another.  Give each loop a unique variable name as its counter.  The following construction is correct:

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

. . .

Next K

Next J

Next I

Note   If you omit counter in a Next statement, execution continues as if you had included it.  If a Next statement is encountered before its corresponding For statement, an error occurs.


See Also

Do...Loop Statement

Exit Statement

For Each...Next Statement

While...Wend Statement


GoSub...Return Statement

See Also	Example

Branches to and returns from a subroutine within a procedure.

Syntax

GoSub line
. . .
line
. . .
Return

The line argument can be any line label or line number.

Remarks

You can use GoSub and Return anywhere in a procedure, but GoSub and the corresponding Return must be in the same procedure.  A subroutine can contain more than one Return statement, but the first Return statement encountered causes the flow of execution to branch back to the statement immediately following the most recently executed GoSub statement.

Note   You can't enter or exit Sub procedures with GoSub...Return.

Tip   Creating separate procedures that you can call may provide a more structured alternative to using GoSub...Return.


See Also

GoTo Statement

On...GoSub Statement

On...GoTo Statement

Sub Statement


GoTo Statement

See Also	Example

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo line

The line argument can be any line label or line number.

Remarks

GoTo can branch only to lines within the procedure where it appears.

Note   Too 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


If...Then...Else Statement

See Also	Example

Conditionally executes a group of statements, depending on the value of an expression.

Syntax

If condition Then statements [Else elsestatements ]

Or, you can use the following, more versatile syntax:

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]] . . .
[Else
[elsestatements]]
End If

The If...Then...Else statement syntax has these parts:

Part	Description

condition	One or more of the following two types of expressions:

A numeric or string expression that evaluates to True or False.  If condition is Null, condition is treated as False.

An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.

statements	One or more statements separated by colons; executed if condition is True.

condition-n	Same as condition.

elseifstatements	One or more statements executed if associated condition-n is True.

elsestatements	One or more statements executed if no previous condition or condition-n expression is True.

Remarks

You can use the single-line form (first syntax) for short, simple tests.  However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note   With the single-line syntax it is possible to have multiple statements executed as the result of an If...Then decision, but they must all 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

When executing a block If (second syntax), condition is tested.  If condition is True, the statements following Then are executed.  If condition is False, each ElseIf condition (if any) is evaluated in turn.  When a True condition is found, the statements immediately following the associated Then are executed.  If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed.  After executing the statements following Then or Else, execution continues with the statement following End If.

The Else and ElseIf clauses are both optional.  You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause.  Block If statements can be nested; that is, contained within one another.

What follows the Then keyword is examined to determine whether or not a statement is a block If.  If anything other than a comment appears after Then on the same line, 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 preceding them.  The block If must end with an End If statement.

Tip   Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can't be used with the Select Case statement.


See Also

Select Case Statement


On...GoSub, On...GoTo Statements

See Also	Example

Branch to one of several specified lines, depending on the value of an expression.

Syntax

On expression GoSub destinationlist

On expression GoTo destinationlist

The On...GoSub and On...GoTo statement syntax has these parts:

Part	Description

expression	Any numeric expression that evaluates to a whole number between 0 and 255, inclusive.  If expression is any number other than a whole number, it is rounded before it is evaluated.

destinationlist	List of line numbers or line labels separated by commas.

Remarks

The value of expression determines which line in destinationlist is branched to.  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:

If expression is	Then
Equal to 0	Control drops to the statement following On...GoSub or On...GoTo.
Greater than number of items in list	Control drops to the statement following On...GoSub or On...GoTo.
Negative	An error occurs.
Greater than 255	An error occurs.
You can mix line numbers and line labels in the same list.  There is no practical limit to the number of line labels and line numbers you can use with On...GoSub and On...GoTo.  However, if you use more labels or numbers than fit on a single line, you must use the line-continuation character to continue the logical line onto the next physical line.

Tip   Select Case provides a more structured and flexible way to perform multiple branching.


See Also

GoSub...Return Statement

GoTo Statement

Select Case Statement


Select Case Statement

See Also	Example

Executes one of several groups of statements, depending on the value of an expression.

Syntax

Select Case testexpression
[Case expressionlist-n
[statements-n]] . . .
[Case Else
[elsestatements]]
End Select

The Select Case statement syntax has these parts:

Part 	Description

testexpression	Any numeric or string expression.

expressionlist-n	Delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression.  The To keyword specifies a range of values.  If you use the To keyword, the smaller value must appear before To.  Use the Is keyword with comparison operators (except Is and Like) to specify a range of values.  If not supplied, the Is keyword is automatically inserted.

statements-n	One or more statements executed if testexpression matches any part of expressionlist-n.

elsestatements	One or more statements executed if testexpression doesn't match any of the Case clause.

Remarks

If testexpression matches any expressionlist expression associated with a Case clause, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to the End Select.  Control then passes to the statement following End Select.  If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the statements 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, execution continues at the statement following End Select.

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

Note   The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings.  In the following example, Case matches strings that are exactly equal to everything, strings that fall between nuts and soup in 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 Statement

On...GoTo Statement


Shell Function

See Also	Example

Runs an executable program.

Syntax

Shell(pathname[, windowstyle])

The Shell function syntax has these named arguments:

Part	Description

pathname	Name of the program to execute and any required arguments or command line switches; may include directory and drive.  May also be the name of a document that has been associated with an executable program.

windowstyle	Number corresponding to the style of the window in which the program is to be run.  If windowstyle is omitted, the program is started minimized with focus.

The windowstyle named argument has these values:

Constant	Value	Description

vbHide	0	Window is hidden and focus is passed to the hidden window.

vbNormalFocus	1	Window has focus and is restored to its original size and position.

vbMinimizedFocus	2	Window is displayed as an icon with focus.

vbMaximizedFocus	3	Window is maximized with focus.

vbNormalNoFocus	4	Window is restored to its most recent size and position. The currently active window remains active.

vbMinimizedNoFocus	6	Window is displayed as an icon. The currently active window remains active.

Remarks

If the Shell function successfully executes the named file, it returns the task identification (ID) of the started program.  The task ID is a unique number that identifies the running program.  If the Shell function can't start the named program, an error occurs.

Note   The Shell function runs other programs asynchronously.  This means you can't depend on a program started with Shell to be finished executing before the statements following the Shell function in your application are executed.


See Also

AppActivate Statement


Stop Statement

See Also	Example

Suspends execution.

Syntax

Stop

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

You can place Stop statements anywhere in procedures to suspend execution.  Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but unlike End, it doesn't close any files or clear variables, unless it is in a compiled executable (.EXE) file.


See Also

End Statement

Make OLE DLL File Command


While...Wend Statement

See Also	Example

Executes a series of statements as long as a given condition is True.

Syntax

While condition
[statements]
Wend

The While...Wend statement syntax has these parts:

Part	Description

condition	Numeric or string expression that evaluates to True or False.  If condition is Null, condition is treated as False.

statements	One or more statements executed while condition is True.

Remarks

If condition is True, all statements in statements 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.

While...Wend loops can be nested to any level.  Each Wend matches the most recent While.

Tip   The Do...Loop statement provides a more structured and flexible way to perform looping.


See Also

Do...Loop Statement

With Statement


With Statement

See Also	Example

Executes a series of statements on a single object or a user-defined type.

Syntax

With object
[statements]
End With

The With statement syntax has these parts:

Part	Description

object	Name of an object or a user-defined type.

statements	One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object.  For example, if you have a number of different properties to change on a single object, it is more convenient to place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment.  The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel

.Height = 2000

.Width = 2000

.Caption = "This is MyLabel"

End With

Note   Once a With block is entered, object can't be changed.  As a result, you can't use a single With statement to affect a number of different objects.

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

Important   Don't jump into or out of With blocks.  You may get errors or unpredictable behavior if statements in a With block are executed, but either the With or End With statement is not executed.


 See Also

Do...Loop Statement

While...Wend Statement


Date Function

See Also	Example

Returns the current system date.

Syntax

Date

Remarks

To set the system date, use the Date statement.


 See Also

CDate Function

Date Statement

Format Function

Now Function

Returning Strings From Functions

Time Function

Time Statement


Date Statement

See Also	Example

Sets the current system date.

Syntax

Date = date

For MS-DOS computers, the date argument must be a date from January 1, 1980 through December 31, 2099, or an error occurs.  For Microsoft Windows NT computers, date must be a date from January 1, 1980 through December 31, 2079.

Remarks

If you use the Date statement to set the date on computers using versions of MS-DOS earlier than version 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 Function

Time Function

Time Statement


DateSerial Function

See Also	Example

Returns a Date for a specified year, month, and day.

Syntax

DateSerial(year, month, day)

The DateSerial function syntax has these named arguments:

Part	Description

year	Number between 100 and 9999, inclusive, or a numeric expression.

month	Any numeric expression.

day	Any numeric expression.

Remarks

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

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

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

For the year argument, values between 0 and 99, inclusive, are interpreted as the years 1900 [image] 1999.  For all other year arguments, use a complete four-digit year (for example, 1800).

When any argument exceeds the normally accepted range for that argument, it increments to the next larger unit as appropriate.  For example, if you specify 35 days, it is evaluated as one month and some number of days, depending on where in the year it is applied.  However, if any single argument is outside the range -32,768 to 32,767, or 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

Date Function

Date Statement

DateValue Function

Day Function

Month Function

Now Function

TimeSerial Function

TimeValue Function

Weekday Function

Year Function


DateValue Function

See Also	Example

Returns a Date.

Syntax

DateValue(date)

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

Remarks

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

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

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


 See Also

CDate Function

Date Function

Date Statement

DateSerial Function

Day Function

Month Function

Now Function

TimeSerial Function

TimeValue Function

Weekday Function

Year Function


Day Function

See Also	Example

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

Syntax

Day(date)

The date argument is any numeric or string expression, or any combination, that can represent a date.  If date contains Null, Null is returned.


 See Also

Date Function

Date Statement

Hour Function

Minute Function

Month Function

Now Function

Second Function

Weekday Function

Year Function


Hour Function

See Also	Example

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

Syntax

Hour(time)

The time argument is any numeric or string expression, or any combination, that can represent a time.  If time contains Null, Null is returned.


 See Also

Day Function

Minute Function

Now Function

Second Function

Time Function

Time Statement


Minute Function

See Also	Example

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

Syntax

Minute(time)

The time argument is any numeric or string expression, or any combination, that can represent a time.  If time contains Null, Null is returned.


 See Also

Day Function

Hour Function

Now Function

Second Function

Time Function

Time Statement


Month Function

See Also	Example

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

Syntax

Month(date)

The date argument is any numeric or string expression, or any combination, that can represent a date.  If date contains Null, Null is returned.


 See Also

Date Function

Date Statement

Day Function

Now Function

Weekday Function

Year Function


Now Function

See Also	Example

Returns the current date and time according to the setting of your computer's system date and time.

Syntax

Now


 See Also

Date Function

Date Statement

Day Function

Hour Function

Minute Function

Month Function

Second Function

Time Function

Time Statement

Weekday Function

Year Function


Second Function

See Also	Example

Returns a whole number between 0 and 59, inclusive, representing the second of the minute.

Syntax

Second(time)

The time argument is any numeric or string expression, or any combination, that can represent a time.  If time contains Null, Null is returned.


 See Also

Day Function

Hour Function

Minute Function

Now Function

Time Function

Time Statement


Time Function

See Also	Example

Returns a Date indicating the current system time.

Syntax

Time

Remarks

To set the system time, use the Time statement.


 See Also

Date Function

Date Statement

Returning Strings From Functions

Time Statement

Timer Function


Time Statement

See Also	Example

Sets the system time.

Syntax

Time = time

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

Remarks

If time is a string, Time attempts to convert it to a time using the time separators you specified for your system.  If it can't be converted to a valid time, an error occurs.

Note   If you use the Time statement to set the time on computers using versions of MS-DOS earlier than version 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 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 Function

Date Statement

Time Function


Timer Function

See Also	Example

Returns the number of seconds elapsed since midnight.

Syntax

Timer


 See Also

Time Function


TimeSerial Function

See Also	Example

Returns a Date containing the time for a specific hour, minute, and second.

Syntax

TimeSerial(hour, minute, second)

The TimeSerial function syntax has these named arguments:

Part	Description

hour	Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.

minute	Any numeric expression.

second	Any numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normally accepted range for the unit; that is, 0 [image] 23 for hours and 0 [image] 59 for minutes and seconds.  However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time.  The following example uses expressions instead of absolute time numbers.  The TimeSerial function returns a time for 15 minutes before (-15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, -15, 0)

When any argument exceeds the normally accepted range for that argument, it increments to the next larger unit as appropriate.  For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes.  However, if any single argument is outside the range -32,768 to 32,767, or if the time specified by the three arguments, either directly or by expression, causes the date to fall outside the acceptable range of dates, an error occurs.


 See Also

DateSerial Function

DateValue Function

Hour Function

Minute Function

Now Function

Second Function

TimeValue Function


TimeValue Function

See Also	Example

Returns a Date containing the time.

Syntax

TimeValue(time)

The time argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive.  However, time can also be any expression that represents a time in that range.  If time contains Null, Null is returned.

Remarks

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 the time argument contains date information, TimeValue doesn't return it.  However, if time includes invalid date information, an error occurs.


 See Also

DateSerial Function

DateValue Function

Hour Function

Minute Function

Now Function

Second Function

TimeSerial Function


Weekday Function

See Also	Example

Returns a whole number representing the day of the week.

Syntax

Weekday(date, [firstdayofweek])

The Weekday function syntax has these named arguments:

Part	Description

date	Numeric or string expression, in any combination, that can represent a date.  If date contains Null, Null is returned.

firstdayofweek	A constant that specifies the first day of the week, as described in Settings.  If omitted, vbSunday is assumed.

Settings

The firstdayofweek argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use NLS API setting.

vbSunday	1	Sunday

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday

Return Values

The Weekday function can return any of these values:

Constant	Value	Description

vbSunday	1	Sunday

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday


 See Also

Date Function

Date Statement

Day Function

Month Function

Now Function

Year Function


Year Function

See Also	Example

Returns a whole number representing the year.

Syntax

Year(date)

The date argument is any numeric or string expression, or any combination, that can represent a date.  If date contains Null, Null is returned.


 See Also

Date Function

Date Statement

Day Function

Month Function

Now Function

Weekday Function


Boolean Data Type

See Also

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

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


 See Also

CBool Function

Data Type Summary

Deftype Statements

Integer Data Type


Byte Data Type

See Also

Byte variables are stored as single, unsigned, 8-bit (1-byte) ranging in value from 0 to 255.

The Byte data type is useful for containing binary data that can be passed to and from dynamic link libraries (DLL) and OLE Automation objects.


See Also

CByte Function

Data Type Summary

Deftype Statements

Integer Data Type


Currency Data Type

See Also

Currency variables are stored as 64-bit (8-byte) numbers in an integer format, 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 Currency is @.

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.


See Also

CCur Function

Data Type Summary

Deftype Statements

Long Data Type


Data Type Summary

See Also

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

Data type	Storage size	Range
Byte	1 byte	0 to 255
Boolean	2 bytes	True or False.
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.
Date	8 bytes	January 1, 100 to December 31, 9999.
Object	4 bytes	Any Object reference.
String (variable-length)	10 bytes + string length	0 to approximately 2 billion (approximately 65,400 for Microsoft Windows version 3.1 and earlier).
String (fixed-length)	Length of string	1 to approximately 65,400.
Variant (with numbers)	16 bytes	Any numeric value up to the range of a Double.
Variant (with characters)	22 bytes + string length	Same range as for variable-length String.
User-defined (using Type)	Number required by elements	The range of each element is the same as the range of its data type.
Note   Arrays of any data type require 20 bytes of memory plus four bytes for each array dimension plus the number of bytes occupied by the data itself.  The memory occupied by the data can be calculated by multiplying the number of data elements by the size of each element.  For example, the data in a single-dimension array consisting of four Integer data elements of two bytes each occupies eight bytes.  The eight bytes the data requires plus the 24 bytes of overhead brings the total memory requirement for the array to 32 bytes.

A Variant containing an array requires 12 bytes more than the array alone.


 See Also

Boolean Data Type

Byte Data Type

Currency Data Type

Date Data Type

Deftype Statements

Double Data Type

Integer Data Type

Long Data Type

Object Data Type

Single Data Type

String Data Type

Type Statement

User-Defined Data Type

Variant Data Type


Date Data Type

See Also

Date variables are stored as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59.  Any recognizable literal date values can be assigned to Date variables.  Literal dates must be enclosed within number sign characters (#), for example, #January 1, 1993# or #1 Jan 93#.

Date variables display dates according to the short date format recognized by your computer.  Times display according to the time format (either 12- or 24-hour) recognized by your computer.

When other numeric data types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time.  Midnight is 0 and midday is .5.  Negative whole numbers represent dates before 30 December 1899.


 See Also

CDate Function

Data Type Summary

Deftype Statements

Double Data Type

Variant Data Type


Double Data Type

See Also

Double(double-precision floating-point) variables are stored as IEEE 64-bit (8-byte) floating-point numbers 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 Double is #.


See Also

CDbl Function

Data Type Summary

Deftype Statements

Single Data Type


Integer Data Type

See Also

Integer variables are stored as 16-bit (2-byte) numbers ranging in value from -32,768 to 32,767.  The type-declaration character for Integer is %.

You can also use Integer variables 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.  For example, when asking the user to select a color from a list, you could have black = 0, white = 1, and so on.  It is good programming practice to define constants using the Const statement for each enumerated value.


See Also

CInt Function

Data Type Summary

Deftype Statements

Long Data Type

Variant Data Type


Long Data Type

See Also

Long (long integer) variables are stored as signed 32-bit (4-byte) numbers ranging in value from -2,147,483,648 to 2,147,483,647.  The type-declaration character for Long is &.


See Also

CLng Function

Data Type Summary

Deftype Statements

Integer Data Type


Object Data Type

See Also

Object variables are stored as 32-bit (4-byte) addresses that refer to OLE Automation objects within an application.  A variable declared as an Object is one that can subsequently be assigned (using the Set statement) to refer to any object produced by the application.


See Also

Data Type Summary

Deftype Statements

IsObject Function

Variant Data Type


Single Data Type

See Also

Single (single-precision floating-point) variables are stored as IEEE 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values.  The type-declaration character for Single is !.


See Also

CSng Function

Data Type Summary

Deftype Statements

Double Data Type

Variant Data Type


String Data Type

See Also

There are two kinds of strings:

Variable-length strings, which can contain up to approximately 2 billion (2^31) characters (approximately 64K (2^16) characters for Microsoft Windows version 3.1 and earlier).

Fixed-length strings, which can contain 1 to approximately 64K (2^16) characters.

Note   Public fixed-length strings can't be used in class modules.

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


See Also

CStr Function

Data Type Summary

Deftype Statements

String Function

Variant Data Type


User-Defined Data Type

See Also

Any data type you define using the Type statement.  User-defined data types can contain one or more elements of any data type, array, or a previously defined user-defined type.  For example:

Type MyType

MyName As String	' String variable stores a name.

MyBirthDate As Date	' Date variable stores a birthdate.

MySex As Integer	' Integer variable stores sex (0 for

End Type	' female, 1 for male).


See Also

Data Type Summary

Type Statement


Variant Data Type

See Also

The Variant data type is the data type that all variables become if not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static).  The Variant data type has no type-declaration character.

The Variant is a special data type that can contain any kind of data except fixed-length String data and user-defined types.  A Variant can also contain the special values Empty, Error, Nothing, and Null.  You can determine how the data in a Variant is treated using the VarType or TypeName function.

Numeric data can be any integer or real number value ranging from -1.797693134862315E308 to -4.94066E-324 for negative values and from 4.94066E-324 to 1.797693134862315E308 for positive values.  Generally, numeric Variant data is maintained in its original 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 a Byte, 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.  A Byte is promoted to an Integer, an Integer is promoted to a Long, and a Long and a Single are promoted to a Double.  An error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

You can use the Variant data type in place of any 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 (assigned an initial value).  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.

In a Variant, Error is a special value used to indicate that an error condition has occurred in a procedure.  However, unlike for other kinds of errors, normal application-level error handling does not occur.  This allows you, or the application itself, to take some alternative based on the error value.  Error values are created by converting real numbers to error values using the CVErr function.


See Also

CVar Function

CVErr Function

Data Type Summary

Deftype Statements

Dim Statement

Nothing Keyword

Operator Summary

Private Statement

Public Statement

Static Statement

TypeName Function

VarType Function


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 [image] 255) using your keyboard.  The first 128 characters (0 [image] 127) correspond to the letters and symbols on a standard U.S. keyboard.  The second 128 characters (128 [image] 255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


argument <definition>
argument

A constant, variable, or expression passed to a procedure.


array <definition>
array

A set of sequentially indexed elements having the same intrinsic data type.  Each element of an array has a unique identifying index number.  Changes made to one element of an array 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 U.S. keyboard.  The ASCII character set is the same as the first 128 characters (0 [image] 127) in the ANSI character set.


automatic formatting <definition>
automatic formatting

A feature that automatically formats code as you enter it by capitalizing the first letter for keywords, regularizing spacing, adding punctuation, and setting the foreground and background colors.


bit-wise comparison <definition>
bit-wise comparison

A bit-by-bit comparison of identically positioned bits in two numeric expressions.


Boolean expression <definition>
Boolean expression

An expression that evaluates to either True or False.


break mode <definition>
break mode

Temporary suspension of program execution while in the development environment.  In break mode, you can examine, debug, reset, step, or continue program execution.  Break mode can be entered by:

Encountering a breakpoint during program execution.

Pressing CTRL+BREAK during program execution.

Encountering a Stop statement or untrapped run-time error during program execution.

Adding a Break When True watch expression.  Execution stops when the value of the watch changes and evaluates to True.

Adding a Break When Changed watch expression.  Execution stops when the value of the watch changes.


breakpoint <definition>
breakpoint

A selected program line at which execution automatically stops.  Breakpoints are not saved with your code.


by reference <definition>
by reference

A way of passing the address, rather than the value, of an argument to a procedure.  This allows the procedure to access the actual variable.  As a result, the variable's actual value can be changed by the procedure to which it is passed.


by value <definition>
by value

A way of passing the value, rather than the address, of an argument to a procedure.  This allows the procedure to access a copy of the variable.  As a result, the variable's actual value can't be changed by the procedure to which it is passed.


character code <definition>
character code

A number that represents a particular character in a set, such as the ANSI character set.


class <definition>
class

The formal definition of an object.  The class acts as the template from which an instance of an object is created at run time.  The class defines the properties of the object and the methods used to control the object's behavior.


class module <definition>
class module

A module containing the definition of a class (its property and method definitions).


Clipboard <definition>
Clipboard

A temporary storage location used to transfer text, graphics, and code.


code module <definition>
code module

A module containing public code that can be shared among all modules in a project.  A code module is referred to as a standard module in later versions of Visual Basic.


collection <definition>
collection

An object that contains a set of related objects.  An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection may vary.


command line <definition>
command line

The path, filename, 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.  In Visual Basic, a comment line generally starts with an apostrophe ('), or you can use 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 can't be used as comparison operators in a Select Case statement.


compile time <definition>
compile time

The moment at which source code is translated to executable code.


conditional compiler constant <definition>
conditional compiler constant

A Visual Basic identifier that is defined using the #Const compiler directive, or defined in the host application, and used by other compiler directives to determine when or if certain blocks of Visual Basic code are compiled.


constant <definition>
constant

A named item that retains a constant value throughout the execution of a program, as opposed to a variable, whose value can change during execution.  Each host application can define its own set of constants.  Additional constants may be defined by the user with the Const statement.  Constants can be used anywhere in your code in place of actual values.  A constant may be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation.  For example:

Const A = "MyString"


Control Panel <definition>
Control Panel

A set of programs that control your system configuration.  You use Control Panel utilities to adjust hardware and software options, such as desktop colors, printer selections, date and number formats, fonts, and locale settings, such as language and system of measurement.


Control-menu box <definition>
Control-menu box

In Microsoft Windows, the box in the upper-left corner of a window that opens the Control menu.

For applications, this menu displays commands that allow you to restore, move, size, minimize, maximize, or close the current application.  In addition, you may be able to switch to or run other Microsoft Windows-based applications.

For windows within an application, this menu displays commands that allow you to size, move, split, or close the active window.


data type <definition>
data type

The characteristic of a variable that determines what kind of data it can hold.  Data types include Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, Object, Variant (default) and user-defined types, as well as specific types of objects.


data type ranges <definition>
data type ranges

Each data type has a specific range of allowed values:

Data type	Range
Byte	0 to 255.
Boolean	True or False.
Integer	-32,768 to 32,767.
Long	-2,147,483,648 to 2,147,483,647.
Single	-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double	-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency	-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
Date	January 1, 100 to December 31, 9999, inclusive.
Object	Any Object reference.
String (variable-length)	Variable-length strings may range in length from 0 to approximately 2 billion characters (approximately 65,535 for Microsoft Windows version 3.1 and earlier).
String (fixed-length)	Fixed-length strings may range in length from 1 to approximately 64K characters.
Variant	Any numeric value up to the range of a Double or any character text.
User-defined Type elements	The range of each element is the same as the range of its data type.


date expression <definition>
date expression

Any expression that can be interpreted as a date.  This includes any combination of date literals, numbers that look like dates, strings that look like dates, and dates returned from functions.  A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 through December 31, 9999.

Dates are stored as part of a real number.  Values to the left of the decimal represent the date; values to the right of the decimal represent the time.  Negative numbers represent dates prior to December 30, 1899.


date literal <definition>
date literal

Any sequence of characters with a valid format that is surrounded by number signs (#).  Valid formats include the universal date format.

For example, #12/31/92# is the date literal that represents December 31, 1992.  Use date literals to maximize portability across national languages.


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 or by the Format function.


dates and times <definition>
dates and times

Dates and times are stored internally as different parts of a real number.

The value to the left of the decimal represents a date between January 1, 100 and December 31, 9999, inclusive.  Negative values represent dates prior to December 30, 1899.

The value to the right of the decimal represents a time between 0:00:00 and 23:59:59, inclusive.  Midday is represented by .5.


declaration <definition>
declaration

Nonexecutable code that names a constant, variable, or procedure and specifies its characteristics (such as data type).  For DLL procedures, declarations specify names, libraries, and arguments.


design time <definition>
design time

The time during which you build an application in the development environment by adding controls, setting control or form properties, and so on.  In contrast, during run time, you interact with the application as a user would.


dynamic data exchange (DDE) <definition>
dynamic data exchange (DDE)

An established protocol for exchanging data through active links between applications that run under Microsoft Windows.


dynamic-link library (DLL) <definition>
dynamic-link library (DLL)

A library of routines loaded and linked into applications at run time.  DLLs are created with other programming languages such as C, MASM, or FORTRAN.


Empty <definition>
Empty

A value that indicates that no beginning value has been assigned to a Variant variable.  Empty variables are 0 in a numeric context, or zero-length in a string context.


error number <definition>
error number

A whole number in the range 0 to 65,535, inclusive, that corresponds to the Number property of the Err object.  When combined with the Name property of the Err object, this number represents a particular error message.


expression <definition>
expression

A combination of keywords, operators, variables, and constants that yield a string, number, or object.  An expression can perform a calculation, manipulate characters, or test data.


file number <definition>
file number

Number used in the Open statement to open a file.  Use file numbers in the range 1 to 255, inclusive, for files not accessible to other applications.  Use file numbers in the range 256 to 511, inclusive, for files accessible from other applications.


focus <definition>
focus

In the Microsoft Windows environment, only one window, form, or control can receive mouse clicks or keyboard input at any one time.  The object that "has the focus" is normally indicated by a highlighted caption or title bar.  The focus can be set by the user or by the application.


host application <definition>
host application

Any application that supports the use of Visual Basic for applications, for example, Microsoft Excel, Microsoft Project, and so on.


insertion point <definition>
insertion point

The place where text is inserted when you type; usually indicated by a text cursor or selection.


keyword <definition>
keyword

A word or symbol recognized as part of the programming language; for example, a statement, function name, or operator.


Legend

 Applies only to object.

 Applies only to collection.

 Applies to both object and collection.


line-continuation character <definition>
line-continuation character

The combination of a space followed by an underscore ( _); used in the development environment to extend a single logical line of code to two or more physical lines.  Note that line-continuation characters can't be used to continue a line of code within a string expression.


line label <definition>
line label

A line label is used to identify a single line of code.  It can be any combination of characters that starts with a letter and ends with a colon.  Line labels are not case-sensitive and must begin in the first column.


line number <definition>
line number

A line number is used to identify a single line of code.  This number can be any combination of digits that is unique within the module where it is used.  Line numbers must begin in the first column.


locale <definition>
locale

The set of information that corresponds to a given language and country.

The system locale affects the way locale-aware functionality behaves, for example, when you display numbers or convert strings to dates.  You set the locale using the Control Panel utilities provided by the operating system.


logic error <definition>
logic error

A programming error that can cause code to produce incorrect results or stop execution.  For example, a logic error can be caused by incorrect variable names, wrong variable types, endless loops, flaws in comparisons, or array problems.


Long data type

A four-byte integer (a whole number between -2,147,483,648 and 2,147,483,647, inclusive).


member <definition>
member

A constituent element of a collection, object, or user-defined type.


method <definition>
method

A procedure that acts on an object.


module <definition>
module

A set of declarations and procedures.


module level <definition>
module level

Describes code in the declarations section of a module.  Any code outside a procedure is referred to as module-level code.  Declarations must be listed first, followed by procedures.  For example:

Dim X As Integer	' This is a module-level variable declaration.

Const RO = "ReadOnly"	' This is a module-level constant declaration.

Type MyType	' This is a module-level user-defined type

' declaration.

MyString As String

MyAge As Integer

End Type


module variable <definition>
module variable

A variable declared outside Function, Sub, or Property procedure code.  Module variables must be declared outside any procedures in the module.  They exist while the module is loaded, and are visible in all procedures in the module.


named argument <definition>
named argument

An argument that has a name that is predefined in the object library.  Instead of providing values for arguments in the order expected by the syntax, you can use named arguments to assign values in any order.  For example, suppose a method accepts three arguments:

DoSomeThing namedarg1, namedarg2, namedarg3

By assigning values to named arguments, you can use the following statement:

DoSomeThing namedarg3 := 4, namedarg2 := 5, namedarg1 := 20

Note that the arguments need not be in their normal positional order.


Null <definition>
Null

A value indicating that a variable contains no valid data.  Null is the result of:

An explicit assignment of Null to a variable.

Any operation between expressions that contain Null.


numeric expression <definition>
numeric expression

Any expression that can be evaluated as a number.  Elements of the expression can include any combination of keywords, variables, constants, and operators that result in a number.


numeric type <definition>
numeric type

Any intrinsic numeric data type (Byte, Boolean, Integer, Long, Currency, Single, Double or Date) or any Variant numeric subtype (Empty, Integer, Long, Single, Double, Currency, Date, Error, Boolean, or Byte).


Object Browser <definition>
Object Browser

A dialog box that lets you examine the contents of an object library to get information about the objects provided.


object expression <definition>
object expression

An expression that specifies a particular object.  This expression can include any of the object's containers.  For example, if your application has an Application object that contains a Document object that contains a Text object, the following are valid object expressions:

Application.Document.Text

Application.Text

Document.Text

Text


object library <definition>
object library

A file with the .OLB extension that provides information to OLE Automation controllers (like Visual Basic) about available OLE Automation objects.  You can use the Object Browser to examine the contents of an object library to get information about the objects provided.


object type <definition>
object type

A type of object exposed by an application through OLE Automation, for example, Application, File, Range, and Sheet.  Refer to the application's documentation (Microsoft Excel, Microsoft Project, Microsoft Word, and so on) for a complete listing of available objects.


OLE Automation object <definition>
OLE Automation object

An object that is exposed to other applications or programming tools through OLE Automation interfaces.


parameter <definition>
parameter

Variable name by which an argument passed to a procedure is known within the procedure.  This variable receives the argument passed into the procedure.  Its scope ends when the procedure ends.


path <definition>
path

A string expression specifying a directory location.  This location may include a drive specification, for example:

C:\MAIN\SUBDIR\MYSUBDIR


pi <definition>
pi

Pi is a mathematical constant equal to approximately 3.1415926535897932.


print zone <definition>
print zone

Print zones begin every 14 columns.  The width of each column is an average of the width of all characters in the point size for the chosen font.


procedure <definition>
procedure

A named sequence of statements executed as a unit.  For example, Function, Property, and Sub are types of procedures.


procedure level <definition>
procedure level

Describes statements located within a Function, Property, or Sub procedure.  Declarations are usually listed first, followed by assignments and other executable code.  For example:

Sub MySub()	' This statement declares a sub procedure block.

Dim A	' This statement starts the procedure block.

A = "My variable"	' Procedure-level code.

Debug.Print A	' Procedure-level code.

End Sub	' This statement ends a sub procedure block.

Note   In contrast, module-level code resides outside any procedure blocks.


project <definition>
project

A set of modules.


property <definition>
property

A named attribute of an object.  Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.


registry <definition>
 registry

In Windows version 3.1, OLE registration information and file associations are stored in the registration database, and program settings are stored in Windows system initialization (.INI) files.  In Windows 95, the Windows registry serves as a central configuration database for user, application, and computer-specific information, including the information previously contained in both the Windows 3.1 registration database and .INI files.


run time <definition>
run time

The time when code is running.  During run time, you interact with the code as a user would.


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.


SCODE <definition>
 SCODE

A long integer value that is used to pass detailed information to the caller of an interface member or API function.  The status codes for OLE interfaces and APIs are defined in FACILITY_ITF.


scope <definition>
scope

Defines the visibility of a variable, procedure, or object.  For example, a variable declared as Public is visible to all procedures in all modules (unless Option Private Module is in effect).  Variables declared in procedures are visible only within the procedure and lose their value between calls unless they are declared Static.


seed <definition>
seed

An initial value used to generate pseudorandom numbers.  For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.


sort order <definition>
sort order

A sequencing principle used to order data, for example, alphabetic, numeric, ascending, descending, and so on.


standard module <definition>
standard module

A module containing only procedure, type, and data declarations and definitions.  Module-level declarations and definitions in a standard module are Public by default.  A standard module is referred to as a code module in earlier versions of Visual Basic.


statement <definition>
statement

A syntactically complete unit that expresses one kind of action, declaration, or definition.  Normally, a statement occupies a single line, although you can use a colon (:) to include more than one statement on a line.  You can also use a line-continuation character( _) to continue a single logical line onto a second physical line.


string comparison <definition>
string comparison

A comparison of two sequences of characters.  Use Option Compare to specify binary or text comparison.  In English, binary comparisons are case-sensitive; text comparisons are not.


string constant <definition>
string constant

Any constant (defined using the Const keyword) consisting of a sequence of contiguous characters interpreted as the characters themselves rather than some numeric value.  For example:

Const A = "MyString"


string expression <definition>
string expression

Any expression that evaluates to a sequence of contiguous characters.  Elements of the expression can include a function that returns a string, a string literal, a string constant, a string variable, a string Variant, or a function that returns a string Variant (VarType 8).


string literal <definition>
string literal

Any expression consisting of a sequence of contiguous characters surrounded by quotation marks that is literally interpreted as the characters within the quotation marks.  For example:

"MyString"


string type <definition>
string type

A data type whose data consists of a sequence of contiguous characters that represent the actual characters themselves rather than some numerical value.  Strings can include letters, numbers, spaces, and punctuation marks.


syntax checking <definition>
syntax checking

A feature that checks your code for correct syntax.  If syntax checking is turned on, a message is displayed when you enter code that contains a syntax error and the suspect code is highlighted.


syntax error <definition>
syntax error

An error that occurs when you enter a line of code that Visual Basic doesn't recognize.

Note   Syntax rules for individual keywords are defined in the Syntax section of the associated Help topic.  To get Help on a keyword from within the development environment, select the keyword and press F1.


time expression <definition>
time expression

Any expression that can be interpreted as a time.  This includes any combination of time literals, numbers that look like times, strings that look like times, and times returned from functions.

Times are stored as part of a real number.  Values to the right of the decimal represent the time.  Midday (12:00 P.M.) is represented by .5.


title bar <definition>
title bar

An area at the top of a window that displays the window's caption or name.


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

none	Boolean

none	Byte

%	Integer

&	Long

!	Single

#	Double

none	Date

@	Currency

$	String

none	Object

none	Variant


type library <definition>
type library

A file or component within another file that contains OLE Automation standard descriptions of exposed objects, properties, and methods.  Object library files (.OLB) contain type libraries.


universal date format <definition>
universal date format

The universal date format is #yyyy-mm-dd hh:mm:ss#.  However, both the date component (#yyyy-mm-dd#) and the time component (#hh:mm:ss#) can be represented separately.


user-defined type <definition>
user-defined type

Any data type defined using the Type statement.  User-defined data types can contain one or more elements of any data type.  Arrays of user-defined and other data types are created using the Dim statement.  Arrays of any type can be included within user-defined types.


variable <definition>
variable

A named storage location that can contain data that can be modified during program execution.  Each variable has a name that uniquely identifies it within its level of scope.  A data type can be specified or not.

Variable names:

Must begin with an alphabetic character.

Can't contain an embedded period or type-declaration character.

Must be unique within the same scope.

Must be no longer than 255 characters.


Variant data type <definition>
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.  All variables become variant types if not explicitly declared as some other type.


variant expression <definition>
variant expression

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


VarType <definition>
VarType

The VarType function returns a value that provides information about the type of data stored in a variable.  The following table shows the equivalent constant, the return value, and a description of the variable:

Constant	Value	Description

vbEmpty	0	Uninitialized

vbNull	1	Contains no valid data

vbInteger	2	Integer

vbLong	3	Long integer

vbSingle	4	Single-precision floating-point number

vbDouble	5	Double-precision floating-point number

vbCurrency	6	Currency

vbDate	7	Date

vbString	8	String

vbObject	9	OLE Automation object

vbError	10	Error

vbBoolean	11	Boolean

vbVariant	12	Variant (used only for arrays of Variants)

vbDataObject	13	Non-OLE Automation object

vbByte	17	Byte

vbArray	8192	Array

Note   The constant vbArray combined with any other constant indicates an array of that type of variable.


watch expression <definition>
watch expression

A user-defined expression that allows you to observe the behavior of a variable or expression.  For example, if both a and b are variables, the following expressions are valid watch expressions:

a

a*b

3*a = b-2

Watch expressions appear in the Watch pane of the Debug window and are automatically updated when you enter break mode.  The Watch pane displays the value of an expression within a given context.  Watch expressions are not saved with your code.


Close Statement

See Also	Example

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

Syntax

Close [filenumberlist]

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

[[#]filenumber][, [#]filenumber] . . .

Remarks

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

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

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


 See Also

End Statement

Open Statement

Reset Statement

Stop Statement


EOF Function

See Also	Example

Returns a value that indicates whether the end of a file has been reached.

Syntax

EOF(filenumber)

The filenumber argument is any valid file number.

Remarks

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

The EOF function returns False unless the end of the file has been reached; then it returns True.  When used with files opened for Random or Binary access, EOF returns False unless the last executed Get statement is unable to read an entire record; then it returns True.


 See Also

BOF, EOF Properties

Get Statement

Input # Statement

Loc Function

LOF Function

Open Statement


FileAttr Function

See Also	Example

Returns file mode or operating system file handle information for files opened using the Open statement.

Syntax

FileAttr(filenumber, returntype)

The FileAttr function syntax has these named arguments:

Part	Description

filenumber	Any valid file number.

returntype	Number indicating the type of information to return.  Specify 1 to return a value indicating the file mode.  Specify 2 to return the operating system file handle.

Return Values

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

Value	File Mode

1	Input

2	Output

4	Random

8	Append

32	Binary


 See Also

GetAttr Function

Open Statement

SetAttr Statement


FreeFile Function

See Also	Example

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

Syntax

FreeFile[(rangenumber)]

The rangenumber argument specifies the range from which the next free file number is to be returned.  Specify a 0 (default) to return a file number in the range 1 to 255, inclusive.  Specify a 1 to return a file number in the range 256 to 511.

Remarks

Use FreeFile when you have to supply a file number and you want to make sure the file number is not already in use.


 See Also

Open Statement


Get Statement

See Also	Example

Reads from an open disk file into a variable.

Syntax

Get [#]filenumber, [recnumber], varname

The Get statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

recnumber	Record number (Random mode files) or byte number (Binary mode files) at which reading begins.

varname	Valid variable name into which data is read.

Remarks

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on.  If you omit recnumber, 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 read.  Delimiting commas must be included, for example:

Get #4,,FileBuffer

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

If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get 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 the record length match the length of the data being read.

If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then the data that goes into the variable.  Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

If the variable being read into is a Variant of numeric type, Get reads 2 bytes identifying the VarType of the Variant and then 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.

Note   You can use the Get statement to read a Variant array from disk but you can't use Get to read a scalar Variant containing an array.  You also can't use Get to read objects from disk.

If the variable being read into is a String Variant (VarType 8), Get reads 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 read into is a dynamic array, Get reads a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the array data and the array descriptor.  For example, the following array declaration requires 118 bytes when the array is written to disk.

Dim MyArray(1 To 5,1 To 10) As Integer

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

If the variable being read into is a fixed-size array, Get reads only the data.  No descriptor is read.

If the variable being read into is any other type of variable (not a variable-length string or 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.

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

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

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.

For any array other than an array in a user-defined type, Get reads only the data.  No descriptor is read.

Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor.  The number of bytes read equals the number of characters already in the string.  For example, the following statements read 10 bytes from file number 1:

VarString = String(10," ")

Get #1,,VarString


 See Also

Input # Statement

Line Input # Statement

Open Statement

Put Statement

Seek Function

Type Statement

VarType Function


Input # Statement

See Also	Example

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

Syntax

Input #filenumber, varlist

The Input # statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

varlist	Comma-delimited list of variables that are assigned values read from the file [image] can't be an array or object variable.  However, variables that describe an element of an array or user-defined type may be used.

Remarks

Use this statement only with files opened in Input or Binary mode.

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

Data	Value assigned to variable
Delimiting comma or blank line	Empty.
#NULL#	Null.
#TRUE# or #FALSE#	True or False.
#yyyy-mm-dd hh:mm:ss#	The date and/or time represented by the expression.
#ERROR errornumber#	errornumber (variable is a Variant tagged as an error).
Double quotation marks (") within input data are ignored.

Data items in a file must appear in the same order as the variables in varlist and match variables of the same data type.  If a variable is numeric and the data is not, a value of zero is assigned to the variable.

If the end of the file is reached while a data item is being input, the input is terminated and an error occurs.

Note   To correctly read data from a file into variables, you should always use the Write # statement instead of the Print # statement to write the data to the files.  Using Write # ensures that each separate data field is properly delimited.


 See Also

Input Function

Open Statement

Print # Statement

Write # Statement


Input Function

See Also	Example

Returns characters from an open sequential or binary file.

Syntax

Input(number, [#]filenumber)

The Input function syntax has these parts:

Part	Description

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

filenumber	Any valid file number.

Remarks

Use this function only with files opened in Input or Binary mode.

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

Note   Another function (InputB) is provided for use with byte data contained within text files.  Instead of specifying the number of characters to return, number specifies the number of bytes.


 See Also

Get Statement

Input # Statement

Returning Strings From Functions


Line Input # Statement

See Also	Example

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

Syntax

Line Input #filenumber, varname

The Line Input # statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

varname	Valid string variable name.

Remarks

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


 See Also

Chr Function

Input # Statement


Loc Function

See Also	Example

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

Syntax

Loc(filenumber)

The filenumber argument is any valid file number.

Remarks

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

File Access	Return Value

Random	Number of the last record read from or written to the file.

Sequential	Current byte position in the file divided by 128.  (Note that information returned by Loc for sequential files is neither used nor required.)

Binary	Position of the last byte read or written.


 See Also

EOF Function

LOF Function

Open Statement


Lock, Unlock Statements

See Also	Example

Controls access by other processes to all or part of a file opened using the Open statement.

Syntax

Lock [#]filenumber[, recordrange]
. . .
Unlock [#]filenumber[, recordrange]

The Lock and Unlock statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

recordrange	The range of records to lock or unlock.

Settings

The recordrange argument settings are:

recnumber | [start] To end

Setting	Description

recnumber	Record number (Random mode files) or byte number (Binary mode files) at which locking or unlocking begins.

start	Number of the first record or byte to lock or unlock.

end	Number of the last record or byte to lock or unlock.

Remarks

The Lock and Unlock statements are used in environments where several processes might need access to the same file.

Lock and Unlock statements are always used in pairs.  The arguments to Lock and Unlock must match exactly.

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on.  If you 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 recnumber locks the entire file; using Unlock without recnumber unlocks the entire file.

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.

Caution   Be sure to remove all locks with an Unlock statement before closing a file or quitting your program.  Failure to remove locks produces unpredictable results.


 See Also

Open Statement


LOF Function

See Also	Example

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

Syntax

LOF(filenumber)

The filenumber argument is any valid file number.

Remarks

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


Open Statement

See Also	Example

Enables input/output (I/O) to a file.

Syntax

Open pathname [For mode] [Access access] [lock] As [#]filenumber [Len=reclength]

The Open statement syntax has these parts:

Part	Description

pathname	String expression that specifies a filename [image] may include directory and drive.

mode	Keyword specifying the file mode: Append, Binary, Input, Output, or Random.

access	Keyword specifying the operations permitted on the open file: Read, Write, or Read Write.

lock	Keyword specifying the operations permitted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.

filenumber	A valid file number in the range 1 to 511, inclusive.  Use the FreeFile function to obtain the next available file number.

reclength	Number less than or equal to 32,767 (bytes).  For files opened for random access, this value is the record length.  For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it.  Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs.

The Len clause is ignored if mode is Binary.

Important   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


Print # Statement

See Also	Example

Writes display-formatted data to a sequential file.

Syntax

Print #filenumber, [outputlist]

The Print # statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

outputlist	Expression or list of expressions to print.

Settings

The outputlist argument settings are:

[{Spc(n) | Tab[(n)]}][expression][charpos]

Setting	Description

Spc(n)	Used to insert space characters in the output, where n is the number of space characters to insert.

Tab(n)	Used to position the insertion point to an absolute column number, where n is the column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.

expression	Numeric or string expressions to print.

charpos	Specifies the insertion point for the next character.  Use a semicolon to specify the insertion point to be immediately after the last character displayed.  Use Tab(n) to position the insertion point to an absolute column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.  If charpos is omitted, the next character is printed on the next line.

Remarks

If you omit outputlist and include only a list separator after filenumber, a blank line is printed to the file.  Multiple expressions can be separated with either a space or a semicolon.  A space has the same effect as a semicolon.

All data written to the file using Print # is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator) and the keywords are written in the language appropriate for the locale specified for your system.

For Boolean data, either True or False is printed.  The True and False keywords are translated, as appropriate, according to the locale setting specified for your system.

Date data is written to the file using the standard short date format recognized by your system.  When either the date or the time component is missing or zero, only the part provided gets written to the file.

Nothing is written to the file if outputlist data is Empty.  However, if outputlist data is Null, Null is written to the file.  Again, the Null keyword is translated, as appropriate.

For Error data, the output appears as Error errorcode.  The Error keyword is translated, as appropriate, when written to the file.

Because Print # writes an image of the data to the file, you must delimit the data so it prints correctly.  If you use Tab with no arguments to move the print position to the next print zone, Print # also writes the spaces between print fields to the file.

Note   If, at some future time, you want to read the data from a file using the Input # statement, use the Write # statement instead of the Print # statement to write the data to the file.  Using Write # ensures the integrity of each separate data field by properly delimiting it, so that it can be read back in using Input #.  Using Write # also ensures that it can be correctly read in any locale.


 See Also

Open Statement

Print Method

Spc Function

Tab Function

Write # Statement


Put Statement

See Also	Example

Writes from a variable to a disk file.

Syntax

Put [#]filenumber, [recnumber], varname

The Put statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

recnumber	Record number (Random mode files) or byte number (Binary mode files) at which writing begins.

varname	Name of variable containing data to be written to disk.

Remarks

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on.  If you omit recnumber, 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.  You must include delimiting commas, for example:

Put #4,,FileBuffer

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 the record length match the length of the data being written.  If the length of the data being written is greater than that specified in the Len clause of the Open statement, an error occurs.

If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the 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 Variant of a numeric type, 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.

Note   You can use the Put statement to write a Variant array to disk but you can't use Put to write a scalar Variant containing an array to disk.  You also can't use Put to write objects to disk.

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 a dynamic array, Put writes a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor.  For example, the following array declaration requires 118 bytes when the array is written to disk.

Dim MyArray(1 To 5,1 To 10) As Integer

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

If the variable being written is a fixed-size array, Put writes only the data.  No descriptor is written to disk.

If the variable being written is any other type of variable (not a variable-length string or 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.

Put writes elements of user-defined types as if each were written individually, except there is no padding between elements. On disk, a dynamic array in a user-defined type written with Put is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2+8 * NumberOfDimensions.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements, including any arrays and their descriptors.

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

The Len clause in the Open statement has no effect.  Put writes all variables to disk contiguously; that is, with no padding between records.

For any array other than an array in a user-defined type, Put writes only the data.  No descriptor is written.

Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor.  The number of bytes written equals the number of characters in the string.  For example, the following statements write 10 bytes to file number 1:

VarString$ = String$(10," ")

Put #1,,VarString$


 See Also

Get Statement

Open Statement

Seek Function

VarType Function


Reset Statement

See Also	Example

Closes all disk files opened using the Open statement.

Syntax

Reset

Remarks

The Reset statement syntax closes all active files opened by the Open statement and writes the contents of all file buffers to disk.


 See Also

Close Statement

End Statement

Open Statement


Seek Function

See Also	Example

Returns the current read/write position within a file opened using the Open statement.

Syntax

Seek(filenumber)

The filenumber argument is any valid file number.

Remarks

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 Statement

See Also	Example

Sets the position for the next read or write within a file opened using the Open statement.

Syntax

Seek [#]filenumber, position

The Seek statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

position	Number in the range 1 to 2,147,483,647, inclusive, that indicates where the next read or write should occur.

Remarks

Record numbers specified in Get and Put statements override file positioning performed 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


Spc Function

See Also	Example

Used with the Print # statement or the Print method to position output.

Syntax

Spc(n)

The n argument is the number of spaces to insert before displaying or printing the next expression in a list.

Remarks

If n is less than the output-line width, the next print position immediately follows the number of spaces printed.  If n is greater than the output-line width, Spc calculates the next print position using the formula:

currentprintposition + (n Mod width)

For example, if the current print position is 24, and the output-line width is 80 and you specify Spc(90), the next print will start at position 34 (current print position + the remainder of 90/80).  If the difference between the current print position and the output-line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates a number of spaces equal to n - (width - currentprintposition).

Note   Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font.  However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.


 See Also

Mod Operator

Print Method

Print # Statement

Space Function

Tab Function

Width # Statement


Tab Function

See Also	Example

Used with the Print # statement or the Print method to position output.

Syntax

Tab[(n)]

The n argument is the column number to tab to before displaying or printing the next expression in a list.  If omitted, Tab moves the cursor to the beginning of the next print zone.  This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator.

Remarks

If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line.  If n is less than 1, Tab moves the print position to column 1.  If n is greater than the output-line width, Tab calculates the next print position using the formula:

n Mod width

For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the remainder of 90/80).  If n is less than the current print position, printing begins on the next line at the calculated print position.  If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

The leftmost print position on an output line is always 1.  When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

Note   Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns.  The width of each column is an average of the width of all characters in the point size for the chosen font.  However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.


 See Also

Mod Operator

Print Method

Print # Statement

Space Function

Spc Function

Width # Statement


Width # Statement

See Also	Example

Assigns an output-line width to a file opened using the Open statement.

Syntax

Width #filenumber, width

The Width statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

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 width is 0.


 See Also

Open Statement

Print # Statement


Write # Statement

See Also	Example

Writes raw data to a sequential file.

Syntax

Write #filenumber, [outputlist]

The Write statement syntax has these parts:

Part	Description

filenumber	Any valid file number.

outputlist	One or more comma-delimited numeric or string expressions to write to a file.

Remarks

If you omit outputlist and include a comma after filenumber, a blank line is printed to the file.  Multiple expressions can be separated with a space, a semicolon, or a comma.  A space has the same effect as a semicolon.

When Write # is used to write data to a file, several universal assumptions are followed so the data can always be read and correctly interpreted using Input #, regardless of locale:

Numeric data is always written using the period (.) as the decimal separator.

For Boolean data, either #TRUE# or #FALSE# is printed.  The True and False keywords are not translated, regardless of locale.

Date data is written to the file using the universal date format.  When either the date or the time component is missing or zero, only the part provided gets written to the file.

Nothing is written to the file if outputlist data is Empty.  However, for Null data, #NULL# is written.

For Error data, the output appears as #ERROR errorcode#.  The Error keyword is not translated, regardless of locale.

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, that is, a carriage return (Chr(13)) or carriage return-linefeed (Chr(13) + Chr (10)), after it has written the final character in outputlist to the file.


 See Also

Chr Function

Input # Statement

Open Statement

Print # Statement


ChDir Statement

See Also	Example

Changes the current directory.

Syntax

ChDir path

The path argument is a string expression that identifies which directory becomes the new default directory. The path may include the drive.  If no drive is specified, ChDir changes the default directory on the current drive.

Remarks

The ChDir statement changes the default directory but not the default drive.  For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

ChDir "D:\TMP"


 See Also

ChDrive Statement

CurDir Function

Dir Function

MkDir Statement

RmDir Statement


ChDrive Statement

See Also	Example

Changes the current drive.

Syntax

ChDrive drive

The drive argument is a string expression that specifies an existing drive.  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.


 See Also

ChDir Statement

CurDir Function

MkDir Statement

RmDir Statement


CurDir Function

See Also	Example

Returns the current path.

Syntax

CurDir[(drive)]

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


 See Also

ChDir Statement

ChDrive Statement

MkDir Statement

Returning Strings From Functions

RmDir Statement


Dir Function

See Also	Example

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

Syntax

Dir[(pathname[, attributes])]

The Dir function syntax has these parts:

Part	Description

pathname	String expression that specifies a filename [image] may include directory and drive.  Null is returned if pathname is not found.

attributes	Constant or numeric expression, the sum of which specifies file attributes.  If omitted, all normal files are returned that match pathname.

Settings

The attributes argument settings are:

Constant	Value	Description

vbNormal	0	Normal.

vbHidden	2	Hidden.

vbSystem	4	System file.

vbVolume	8	Volume label; if specified, all other attributes are ignored.

vbDirectory	16	Directory.

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

Remarks

Dir supports the use of * (multiple character) and ? (single character) wildcards to specify multiple files. You must specify pathname the first time you call the Dir function, or an error occurs.  If you also specify file attributes, pathname must be included.

Dir returns the first filename that matches pathname.  To get any additional filenames that match pathname, call Dir again with no arguments.  When no more filenames match, Dir returns a zero-length string.  Once a zero-length string is returned, you must specify pathname in subsequent calls or an error occurs.  You can change to a new pathname without retrieving all of the filenames that match the current pathname.  However, you can't recursively call the Dir function.

Tip   Because filenames are retrieved in no particular order, you may want to store returned filenames in an array and then sort the array.  Also, calling Dir with the vbDirectory attribute does not continually return subdirectories.


 See Also

ChDir Statement

CurDir Function

Like Operator

Returning Strings From Functions


FileCopy Statement

See Also	Example

Copies a file.

Syntax

FileCopy source, destination

The FileCopy statement syntax has these named arguments:

Part	Description

source	String expression that specifies the name of the file to be copied.  The source may include directory and drive.

destination	String expression that specifies the target filename.  The destination may include directory and drive.

Remarks

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


 See Also

Kill Statement

Name Statement


FileDateTime Function

See Also	Example

Returns a date (VarType 7) that indicates the date and time when a file was created or last modified.

Syntax

FileDateTime(pathname)

The pathname argument is a string expression that specifies a filename.  The pathname may include the directory and the drive.


 See Also

FileLen Function

GetAttr Function

VarType Function


FileLen Function

See Also	Example

Returns the length of a file in bytes.

Syntax

FileLen(pathname)

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

Remarks

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

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


 See Also

FileDateTime Function

GetAttr Function

LOF Function


GetAttr Function

See Also	Example

Returns a number representing the attributes of a file or directory.

Syntax

GetAttr(pathname)

The pathname argument is a string expression that specifies a filename. The pathname may include the directory and the drive.

Return Values

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

Value	Constant	Description

0	vbNormal	Normal.

1	vbReadOnly	Read-only.

2	vbHidden	Hidden.

4	vbSystem	System file.

16	vbDirectory	Directory.

32	vbArchive	File has changed since last backup.

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

Remarks

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 return value of the following And expression is zero if the Archive attribute is not set:

Result = GetAttr(FName) And vbArchive

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


 See Also

And Operator

FileAttr Function

SetAttr Statement


Kill Statement

See Also	Example

Deletes files from a disk.

Syntax

Kill pathname

The pathname argument is a string expression that specifies one or more filenames to be deleted.  The pathname may include the directory and the drive.

Remarks

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

If you try to use Kill to delete an open file, an error occurs.

To delete directories, use the RmDir statement.


 See Also

Like Operator

RmDir Statement


MkDir Statement

See Also	Example

Creates a new directory.

Syntax

MkDir path

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

Remarks

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.


 See Also

ChDir Statement

CurDir Function

RmDir Statement


Name Statement

See Also	Example

Renames a disk file or directory.

Syntax

Name oldpathname As newpathname

The Name statement syntax has these parts:

Part	Description

oldpathname	String expression that specifies the existing filename and location [image] may include directory and drive.

newpathname	String expression that specifies the new filename and location [image] may include directory and drive.  The filename specified by newpathname can't already exist.

Remarks

Both newpathname and oldpathname must be on the same drive.  If the path in newpathname exists and is different from the path in oldpathname, the Name statement moves the file to the new directory and renames the file, if necessary.  If newpathname and oldpathname have different paths and the same filename, Name moves the file to the new location and leaves the filename unchanged.  Using Name, you can move a file from one directory to another, but you can't move a directory.

Using Name on an open file produces an error.  You must close an open file before renaming it.


 See Also

Kill Statement


RmDir Statement

See Also	Example

Removes an existing directory.

Syntax

RmDir path

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

Remarks

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


 See Also

ChDir Statement

CurDir Function

Kill Statement

MkDir Statement


SetAttr Statement

See Also	Example

Sets attribute information for a file.

Syntax

SetAttr pathname, attributes

The SetAttr statement syntax has these named arguments:

Part	Description

pathname	String expression that specifies a filename [image] may include directory and drive.

attributes	Constant or numeric expression, the sum of which specifies file attributes.

Settings

The  attributes argument settings are:

Constant	Value	Description

vbNormal	0	Normal (default).

vbReadOnly	1	Read-only.

vbHidden	2	Hidden.

vbSystem	4	System file.

vbArchive	32	File has changed since last backup.

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

Remarks

A run-time error occurs if you try to set the attributes of an open file.


 See Also

FileAttr Function

GetAttr Function


Arrays Keyword Summary


Arrays Keyword Summary

See Also

Action	Keywords

Verify an array.	IsArray

Create an array.	Array

Change default lower limit.	Option Base

Declare and initialize an array.	Dim, Private, Public, ReDim, Static

Find the limits of an array.	LBound, UBound

Reinitialize an array.	Erase, ReDim


See Also

Keywords by Task


Collection Object Keyword Summary


Collection Object Keyword Summary

See Also

Action	Keywords

Create a Collection object.	Collection

Add an object to a collection.	Add

Remove an object from a collection.	Remove

Reference an item in a collection.	Item


See Also

Keywords by Task


Compiler Directive Keyword Summary


Compiler Directive Keyword Summary

See Also

Action	Keywords

Define conpiler constant.	#Const

Compile selected blocks of code.	#If...Then...#Else


See Also

Keywords by Task


Control Flow Keyword Summary


Control Flow Keyword Summary

See Also

Action	Keywords

Branch.	GoSub...Return, GoTo, On Error, On...GoSub, On...GoTo

Exit or pause the program.	DoEvents, End, Exit, Stop

Loop.	Do...Loop, For...Next, For Each...Next, While...Wend, With

Make decisions.	Choose, If...Then...Else, Select Case, Switch

Procedures.	Call, Function...End Function, Property Get...End Property, Property Let...End Property, Property Set...End Property, Sub...End Sub


See Also

Keywords by Task


Conversion Keyword Summary


Conversion Keyword Summary

See Also

Action	Keywords

ANSI value to string.	Chr

Convert to lowercase or uppercase.	Format, LCase, UCase

Date to serial number.	DateSerial, DateValue

Decimal number to other bases.	Hex, Oct

Number to string.	Format, Str

One data type to another.	CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVErr, Fix, Int

Serial number to date.	Date, Month, Weekday, Year

Serial number to time.	Hour, Minute, Second

String to ASCII value.	Asc

String to number.	Val

Time to serial number.	TimeSerial, TimeValue


See Also

Keywords by Task


Data Types Keyword Summary


Data Types Keyword Summary

See Also

Action	Keywords

Convert between data types.	CBool, CByte, CCur, CDate, CDbl, CInt, CLng, CSng, CStr, CVar, CVErr, Fix, Int

Setting intrinsic data types.	Boolean, Byte, Currency, Date, Double, Integer, Long, Object, Single, String, Variant (default)

Verifying data types.	IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject


See Also

Keywords by Task


Dates and Times Keyword Summary


Dates and Times Keyword Summary

See Also

Action	Keywords

Get the current date or time.	Date, Now, Time

Return a date.	DateSerial, DateValue

Return a time.	TimeSerial, TimeValue

Set the date or time.	Date, Time

Time a process.	Timer

Perform date calculations.	DateAdd, DateDiff, DatePart


See Also

Keywords by Task


Directories and Files Keyword Summary


Directories and Files Keyword Summary

See Also

Action	Keywords

Change directory or folder.	ChDir

Change the drive.	ChDrive

Copy a file.	FileCopy

Make directory or folder.	MkDir

Remove directory or folder.	RmDir

Return current path.	CurDir

Return file, directory, label attributes.	GetAttr

Return file name or volume label.	Dir

Return file date/time stamp.	FileDateTime

Return file length.	FileLen

Rename a file, directory, or folder.	Name

Set attribute information for a file.	SetAttr


See Also

Keywords by Task


Errors Keyword Summary


Errors Keyword Summary

See Also

Action	Keywords

Get error messages.	Error

Provide error information.	Err

Generate run-time errors.	Clear, Error, Raise

Trap errors during run time.	On Error, Resume

Type verification.	IsError

Return Error variant.	CVErr


See Also

Keywords by Task


Financial Keyword Summary


Financial Keyword Summary

See Also

Action	Keywords

Calculate depreciation.	DDB, SLN, SYD

Calculate future value.	FV

Calculate payments.	IPmt, Pmt, PPmt

Calculate number of periods.	NPer

Calculate internal rate of return.	IRR, MIRR

Calculate present value.	NPV, PV

Calculate interest rate.	Rate


See Also

Keywords by Task


Input and Output Keyword Summary


Input and Output Keyword Summary

See Also

Action	Keywords

Access or create a file.	Open

Close files.	Close, Reset

Control output appearance.	Format, Print, Print #, Spc, Tab, Width #

Copy a file.	FileCopy

Get information about a file.	EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF, Seek

Manage files.	Dir, Kill, Lock, Unlock, Name

Read from a file.	Get, Input, Input #, Line Input #

Return length of a file.	FileLen

Set or get file attributes.	FileAttr, GetAttr, SetAttr

Set read-write position in a file.	Seek

Write to a file.	Print #, Put, Write #


See Also

Keywords by Task


Math Keyword Summary


Math Keyword Summary

See Also

Action	Keywords

Derive trigonometric functions.	Atn, Cos, Sin, Tan

General calculations.	Exp, Log, Sqr

Generate random numbers.	Randomize, Rnd

Get absolute value.	Abs

Get the sign of an expression.	Sgn

Perform numeric conversions.	Fix, Int


See Also

Keywords by Task


Miscellaneous Keyword Summary


Miscellaneous Keyword Summary

See Also

Action	Keywords

Process pending events.	DoEvents

Run other programs.	AppActivate, Shell

Send keystrokes to an application.	SendKeys

Sound a beep from computer.	Beep

System.	Command, Environ

OLE Automation.	CreateObject, GetObject


See Also

Keywords by Task


Operators Keyword Summary


Operators Keyword Summary

See Also

Action	Keywords

Arithmetic.	^, -, *,  /, \, Mod, +, &

Comparison.	=, <>, <, >, <=, >=, Like, Is

Logical operations.	Not, And, Or, Xor, Eqv, Imp


See Also

Keywords by Task


String Manipulation Keyword Summary


String Manipulation Keyword Summary

See Also

Action	Keywords

Compare two strings.	StrComp

Convert to lowercase or uppercase.	Format, LCase, UCase

Create string of repeating character.	Space, String

Find length of a string.	Len

Format a string.	Format

Justify a string.	LSet, RSet

Manipulate strings.	Instr, Left, LTrim, Mid, Right, RTrim, Trim

Set string comparison rules.	Option Compare

Work with ASCII and ANSI values.	Asc, Chr

Convert strings.	StrConv

Color and shapes.	Circle, Line, PSet, QBColor, RGB


See Also

Keywords by Task


Variables and Constants Keyword Summary


Variables and Constants Keyword Summary

See Also

Action	Keywords

Assign value.	Let

Declare variables or constants.	Const, Dim, Private, Public, New, Static

Declare module as private.	Option Private Module

Get information about a variant.	IsArray, IsDate, IsEmpty, IsError, IsMissing, IsNull, IsNumeric, IsObject, TypeName, VarType

Require explicit variable declarations.	Option Explicit

Set default data type.	Deftype

Refer to current object	Me


See Also

Keywords by Task


IsArray Function

See Also	Example

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

Syntax

IsArray(varname)

The varname argument can be any variable.

Remarks

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


See Also

Array Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

TypeName Function

Variant Data Type

VarType Function


IsDate Function

See Also	Example

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

Syntax

IsDate(expression)

The expression argument can be any date or string expression recognizable as a date or time.

Remarks

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


 See Also

CDate Function

Date Data Type

IsArray Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

TypeName Function

Variant Data Type

VarType Function


IsEmpty Function

See Also	Example

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

Syntax

IsEmpty(expression)

The expression argument can be any numeric or string expression.  However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

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


 See Also

IsArray Function

IsDate Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

TypeName Function

Variant Data Type

VarType Function


IsError Function

See Also	Example

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

Syntax

IsError(expression)

The expression argument must be a Variant of VarType vbError.

Remarks

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


See Also

CVErr Function

IsArray Function

IsDate Function

IsEmpty Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

TypeName Function

Variant Data Type

VarType Function


IsMissing Function

See Also	Example

Returns a Boolean value indicating whether an optional argument has been passed to a procedure.

Syntax

IsMissing(argname)

The argname argument is the name of an optional procedure argument.

Remarks

The IsMissing function is used in a procedure that has optional arguments, including ParamArray arguments, to determine whether an argument has been passed to the procedure.  IsMissing returns True if no value has been passed for the specified argument; otherwise, it returns False.  If IsMissing returns True for an argument, use of the missing argument in other code may cause a user-defined error.  If IsMissing is used on a ParamArray argument, it always returns False.


See Also

Function Statement

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsNull Function

IsNumeric Function

IsObject Function

ParamArray Keyword

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement

TypeName Function

Variant Data Type

VarType Function


IsNull Function

See Also	Example

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

Syntax

IsNull(expression)

The expression argument can be any numeric or string expression.

Remarks

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

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

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


 See Also

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNumeric Function

IsObject Function

TypeName Function

Variant Data Type

VarType Function


IsNumeric Function

See Also	Example

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

Syntax

IsNumeric(expression)

The expression argument can be any numeric or string expression.

Remarks

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

IsNumeric returns False if expression is a date expression.


 See Also

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsObject Function

TypeName Function

Variant Data Type

VarType Function


IsObject Function

See Also	Example

Returns a Boolean value indicating whether an expression references a valid OLE Automation object.

Syntax

IsObject(expression)

The expression argument can be any expression.

Remarks

IsObject returns True if expression is a variable of Object type (or a Variant of VarType vbObject, or a user-defined object); otherwise, it returns False.


See Also

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

Object Data Type

Set Statement

TypeName Function

Variant Data Type

VarType Function


TypeName Function

See Also	Example

Returns a string that provides information about a variable.

Syntax

TypeName(varname)

The varname argument can be any variable except a variable of a user-defined type.

Remarks

The string returned by TypeName can be any one of the following:

String Returned	Variable contains

objecttype	An OLE Automation object whose type is objecttype.

Byte	A byte

Integer 	An integer.

Long	A long integer.

Single	A single-precision floating-point number.

Double	A double-precision floating-point number.

Currency	A currency value.

Date	A date.

String	A string.

Boolean	A Boolean value.

Error	An error value.

Empty	Uninitialized.

Null	No valid data.

Object	An object that supports OLE Automation.

Unknown	An OLE Automation object whose type is unknown.

Nothing	An object variable that doesn't refer to an object.

If varname is an array, the returned string can be any one of the possible returned strings (or Variant) with empty parentheses appended.  For example, if varname is an array of integers, TypeName returns "Integer()".


 See Also

Data Type Summary

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

Variant Data Type

VarType Function


VarType Function

See Also	Example

Returns a value indicating the subtype of a variable.

Syntax

VarType(varname)

The varname argument can be any variable except a variable of a user-defined type.

Return Values

Constant	Value	Variable type description

vbEmpty	0	Empty (uninitialized).

vbNull	1	Null (no valid data).

vbInteger	2	Integer.

vbLong	3	Long integer.

vbSingle	4	Single-precision floating-point number.

vbDouble	5	Double-precision floating-point number.

vbCurrency	6	Currency.

vbDate	7	Date.

vbString	8	String.

vbObject	9	OLE Automation object.

vbError	10	Error.

vbBoolean	11	Boolean.

vbVariant	12	Variant (used only with arrays of Variants).

vbDataObject	13	Non-OLE Automation object.

vbByte	17	Byte

vbArray	8192	Array.

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

Remarks

The VarType function never returns the value for vbArray by itself.  It is always added to some other value to indicate an array of a particular type.  The constant vbVariant is only returned in conjunction with vbArray to indicate that the argument to the VarType function is an array of type Variant.  For example, the value returned for an array of integers is calculated as vbInteger + vbArray, or 8194.  If an object has a default property, VarType (object) returns the type of its default property.


 See Also

Data Type Summary

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

TypeName Function

Variant Data Type


As <keyword>
As

The As keyword is used in these contexts:

Const Statement

Declare Statement

Dim Statement

Function Statement

Name Statement

Open Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

ReDim Statement

Static Statement

Sub Statement

Type Statement


Binary <keyword>
Binary

The Binary keyword is used in these contexts:

Open Statement

Option Compare Statement


ByRef <keyword>
ByRef

The ByRef keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ByVal <keyword>
ByVal

The ByVal keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Date <keyword>
Date

The Date keyword is used in these contexts:

Date Data Type

Date Function

Date Statement


Else <keyword>
Else

The Else keyword is used in these contexts:

If...Then...Else Statement

Select Case Statement


Empty <keyword>
Empty

See Also

The Empty keyword is used as a Variant subtype.  It indicates an uninitialized variable value.


See Also

Variant Data Type


Error <keyword>
Error

The Error keyword is used in these contexts:

Error Function

Error Statement

On Error Statement


False <keyword>
False

The False keyword has a value equal to 0.


For <keyword>
For

The For keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

Open Statement


Get <keyword>
Get

The Get keyword is used in these contexts:

Get Statement

Property Get Statement


Input <keyword>
Input

The Input keyword is used in these contexts:

Input Function

Input # Statement

Line Input # Statement

Open Statement


Is <keyword>
Is

The Is keyword is used in these contexts:

If ... Then ... Else Statement

Is Operator

Select Case Statement


Len <keyword>
Len

The Len keyword is used in these contexts:

Len Function

Open Statement


Let <keyword>
Let

The Let keyword is used in these contexts:

Let Statement

Property Let Statement


Lock <keyword>
Lock

The Lock keyword is used in these contexts:

Lock, Unlock Statements

Open Statement


Mid <keyword>
Mid

The Mid keyword is used in these contexts:

Mid Function

Mid Statement


Next <keyword>
Next

The Next keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

On Error Statement

Resume Statement


Null <keyword>
Null

See Also

The Null keyword is used as a Variant subtype.  It indicates that a variable contains no valid data.


See Also

Variant Data Type


On <keyword>
On

The On keyword is used in these contexts:

On Error Statement

On...GoSub Statement

On...GoTo Statement


Option <keyword>
Option

The Option keyword is used in these contexts:

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement


Optional <keyword>
Optional

The Optional keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ParamArray <keyword>
ParamArray

The ParamArray keyword is used in these contexts:

Declare Statement

Function Statement

Sub Statement


Print <keyword>
Print

The Print keyword is used in these contexts:

Print Method

Print # Statement


Private <keyword>
Private

The Private keyword is used in these contexts:

Const Statement

Declare Statement

Function Statement

Option Private Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement

Type Statement


Property <keyword>
Property

The Property keyword is used in these contexts:

Property Get Statement

Property Let Statement

Property Set Statement


Public <keyword>
Public

The Public keyword is used in these contexts:

Const Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Sub Statement

Type Statement


Resume <keyword>
Resume

The Resume keyword is used in these contexts:

On Error Statement

Resume Statement


Seek <keyword>
Seek

The Seek keyword is used in these contexts:

Seek Function

Seek Statement


Set <keyword>
Set

The Set keyword is used in these contexts:

Set Statement

Property Set Statement


Static <keyword>
Static

The Static keyword is used in these contexts:

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Static Statement

Sub Statement


Step <keyword>
Step

The Step keyword is used in these contexts:

For...Next Statement

For Each...Next Statement


String <keyword>
String

The String keyword is used in these contexts:

String Data Type

String Function


Then <keyword>
Then

The Then keyword is used in these contexts:

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

If...Then...Else Statement


Time <keyword>
Time

The Time keyword is used in these contexts:

Time Function

Time Statement


To <keyword>
To

The To keyword is used in these contexts:

Dim Statement

For...Next Statement

Lock, Unlock Statements

Private Statement

Public Statement

ReDim Statement

Select Case Statement

Static Statement

Type Statement


True <keyword>
True

The True keyword has a value equal to -1.


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)

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

Remarks

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


See Also

Math Functions

Sgn Function


Atn Function

See Also	Example

Returns the arctangent of a number.

Syntax

Atn(number)

The number argument can be any valid numeric expression.

Remarks

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

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

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

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


See Also

Cos Function

Derived Math Functions

Math Functions

Sin Function

Tan Function


Cos Function

See Also	Example

Returns the cosine of an angle.

Syntax

Cos(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

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

The result lies in the range -1 to 1.

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


See Also

Atn Function

Derived Math Functions

Math Functions

Sin Function

Tan Function


Exp Function

See Also	Example

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

Syntax

Exp(number)

The number argument can be any valid numeric expression.

Remarks

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

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


See Also

Derived Math Functions

Log Function

Math Functions


Int, Fix Functions

See Also	Example

Returns the integer portion of a number.

Syntax

Int(number)

Fix(number)

The number argument can be any valid numeric expression.  If number contains Null, Null is returned.

Remarks

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

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

Fix(number) is equivalent to:

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


See Also

CInt Function

Math Functions


Log Function

See Also	Example

Returns the natural logarithm of a number.

Syntax

Log(number)

The number argument can be any valid numeric expression greater than 0.

Remarks

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

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

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

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

Static Function Log10(X)

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

End Function


See Also

Derived Math Functions

Exp Function

Math Functions


Randomize Statement

See Also	Example

Initializes the random-number generator.

Syntax

Randomize [number]

The number argument can be any valid numeric expression.

Remarks

Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value.  If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.

Note   To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument.  Using Randomize with the same value for number does not repeat the previous sequence.


See Also

Rnd Function

Timer Function


Rnd Function

See Also	Example

Returns a random number.

Syntax

Rnd[(number)]

The number argument can be any valid numeric expression.

Remarks

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

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

If number is	Rnd generates

Less than zero	The same number every time, using number as the seed.

Greater than zero	The next random number in the sequence.

Equal to zero	The most recently generated number.

Not supplied	The next random number in the sequence.

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

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

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Note   To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument.  Using Randomize with the same value for number does not repeat the previous sequence.


See Also

Math Functions

Randomize Statement

Timer Function


Sgn Function

See Also	Example

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

The number argument can be any valid numeric expression.

Return Values

If number is	Sgn returns

Greater than zero	 1

Equal to zero	 0

Less than zero	-1

Remarks

The sign of the number argument determines the return value of the Sgn function.


See Also

Abs Function

Math Functions


Sin Function

See Also	Example

Returns the sine of an angle.

Syntax

Sin(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

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

The result lies in the range -1 to 1.

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


See Also

Atn Function

Cos Function

Derived Math Functions

Math Functions

Tan Function


Sqr Function

See Also	Example

Returns the square root of a number.

Syntax

Sqr(number)

The number argument can be any valid numeric expression greater than or equal to 0.


See Also

Math Functions


Tan Function

See Also	Example

Returns the tangent of an angle.

Syntax

Tan(number)

The number argument can be any valid numeric expression that expresses an angle in radians.

Remarks

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

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


See Also

Atn Function

Cos Function

Derived Math Functions

Math Functions

Sin Function


Derived Math Functions

See Also

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

Function	Derived equivalents

Secant	Sec(X) = 1 / Cos(X)

Cosecant	Cosec(X) = 1 / Sin(X)

Cotangent	Cotan(X) = 1 / Tan(X)

Inverse Sine	Arcsin(X) = Atn(X / Sqr(-X * X + 1))

Inverse Cosine	Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)

Inverse Secant	Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn((X) -1) * (2 * Atn(1))

Inverse Cosecant	Arccosec(X) = Atn(X / Sqr(X * X - 1)) + (Sgn(X) - 1) * (2 * Atn(1))

Inverse Cotangent	Arccotan(X) = Atn(X) + 2 * Atn(1)

Hyperbolic Sine	HSin(X) = (Exp(X) - Exp(-X)) / 2

Hyperbolic Cosine	HCos(X) = (Exp(X) + Exp(-X)) / 2

Hyperbolic Tangent	HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))

Hyperbolic Secant	HSec(X) = 2 / (Exp(X) + Exp(-X))

Hyperbolic Cosecant	HCosec(X) = 2 / (Exp(X) - Exp(-X))

Hyperbolic Cotangent	HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))

Inverse Hyperbolic Sine	HArcsin(X) = Log(X + Sqr(X * X + 1))

Inverse Hyperbolic Cosine	HArccos(X) = Log(X + Sqr(X * X - 1))

Inverse Hyperbolic Tangent	HArctan(X) = Log((1 + X) / (1 - X)) / 2

Inverse Hyperbolic Secant	HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)

Inverse Hyperbolic Cosecant	HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)

Inverse Hyperbolic Cotangent	HArccotan(X) = Log((X + 1) / (X - 1)) / 2

Logarithm to base N	LogN(X) = Log(X) / Log(N)


See Also

Atn Function

Cos Function

Exp Function

Log Function

Sin Function

Sqr Function

Tan Function


Character Set (0 - 127)

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.


CreateObject Function

See Also	Example

Creates an OLE Automation object.

Syntax

CreateObject(class)

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

Part	Description

appname	The name of the application providing the object.

objecttype	The type or class of object to create.

Remarks

Every 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.

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

Dim WordBasicObject As Object

Set WordBasicObject = CreateObject("Word.Basic")

When this code is executed, the application creating the object is started (Microsoft Word in this example).  If it is already running, a new instance of the application is started, and an object of the specified type is created.  Once an object is created, you reference it in code using the object variable you defined.  In the above example, you access properties and methods of the new object using the object variable, WordBasicObject.  For example:

WordBasicObject.Insert "Hello, world."

WordBasicObject.FilePrint

WordBasicObject.FileSaveAs "C:\DOCS\TEST.DOC"

Similarly, you can pass the object returned by the CreateObject function to a function expecting an object as an argument.  For example:

Call MySub (CreateObject("Word.Basic"))

Note   Use CreateObject when there is no current instance of the object. If there is a current instance, or if you want to start the application and have it load a file, you can use the GetObject function.

If an object has registered itself as a single-instance object (for example, the Word.Basic object in Microsoft Word 6.0), only one instance of the object is created, no matter how many times CreateObject is executed.


 See Also

GetObject Function

OLE Automation

Set Statement

Working Across Applications


GetObject Function

See Also	Example

Retrieves an OLE Automation object from a file.

Syntax

GetObject([pathname][, class])

The GetObject function syntax has these named arguments:

Part	Description

pathname	The full path and name of the file containing the object to retrieve.  If pathname is omitted, class is required.

class	A string representing the class of the object.

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

Part	Description

appname	The name of the application providing the object.

objecttype	The type or class of object to create.

Remarks

Use the GetObject function to access an OLE Automation object from a file and assign the object to an object variable.  To do this, use the Set statement to assign the object returned by GetObject to the object variable.  For example:

Dim CADObject As Object

Set CADObject = GetObject("C:\CAD\SCHEMA.CAD")

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

If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type.  If the pathname argument is omitted entirely, GetObject returns a currently active object of the specified type.  If no object of the specified type exists, 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 filename and follow it with a string that identifies the part of the file you want to activate.  For information on how to create this string, see the documentation for the application that created the object.

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

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

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

Dim MyObject As Object

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

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

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

MyObject.Line 9, 90

MyObject.InsertText 9, 100, "Hello, world."

MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"

Note   Use the GetObject function when there is a current instance of the object, or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function.

If an object has registered itself as a single-instance object (for example, the Word.Basic object in Microsoft Word 6.0), only one instance of the object is created, no matter how many times CreateObject is executed.  In addition, with a single-instance object, GetObject always returns the same instance when called with the zero-length string syntax (""), and it causes an error if the pathname argument is omitted.  You can't use GetObject to obtain a reference to a class created with Visual Basic.


 See Also

CreateObject Function

OLE Automation

Set Statement

Working Across Applications


Visual Basic for Applications Constants

See Also

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

Compiler Constants

Date Constants

Dir, GetAttr, and SetAttr Constants

IMEStatus Constants

MsgBox Constants

Shell Constants

StrConv Constants

VarType Constants


See Also

Data Access Constants

DateDiff Function

DatePart Function

Dir Function

Format Function

GetAttr Function

IMEStatus Function

MsgBox Function

SetAttr Statement

Shell Function

StrConv Function

VarType Function

Visual Basic Constants

Weekday Function


Compiler Constants

See Also

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

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

Constant	Value	Description

Win16	True	Indicates that the development environment is 16-bit.

Win32	False	Indicates that the development environment is not 32-bit.

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

Constant	Value	Description

Win16	False	Indicates that the development environment is not 16-bit.

Win32	True	Indicates that the development environment is 32-bit.

Note   Because the constants defined here are provided by Visual Basic, you can't define your own constants at any level with these same names.


See Also

#Const Directive

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

Visual Basic for Applications Constants


VarType Constants

See Also

Constant	Value	Description

vbEmpty	0	Uninitialized (default).

vbNull	1	Contains no valid data.

vbInteger	2	Integer.

vbLong	3	Long integer.

vbSingle	4	Single-precision floating-point number.

vbDouble	5	Double-precision floating-point number.

vbCurrency	6	Currency.

vbDate	7	Date.

vbString	8	String.

vbObject	9	OLE Automation object.

vbError	10	Error.

vbBoolean	11	Boolean.

vbVariant	12	Variant (used only for arrays of Variants).

vbDataObject	13	Non-OLE Automation object.

vbByte	17	Byte

vbArray	8192	Array.


See Also

VarType Function

Visual Basic for Applications Constants


MsgBox Constants

See Also

MsgBox Arguments

Constant	Value	Description

vbOKOnly	0	OK button only (default).

vbOKCancel	1	OK and Cancel buttons.

vbAbortRetryIgnore	2	Abort, Retry, and Ignore buttons.

vbYesNoCancel	3	Yes, No, and Cancel buttons.

vbYesNo	4	Yes and No buttons.

vbRetryCancel	5	Retry and Cancel buttons.

vbCritical	16	Critical message.

vbQuestion	32	Warning query.

vbExclamation	48	Warning message.

vbInformation	64	Information message.

vbDefaultButton1	0	First button is default (default).

vbDefaultButton2	256	Second button is default.

vbDefaultButton3	512	Third button is default.

vbApplicationModal	0	Application modal message box (default).

vbSystemModal	4096	System modal message box.

MsgBox Return Values

Constant	Value	Description

vbOK	1	OK button pressed.

vbCancel	2	Cancel button pressed.

vbAbort	3	Abort button pressed.

vbRetry	4	Retry button pressed.

vbIgnore	5	Ignore button pressed.

vbYes	6	Yes button pressed.

vbNo	7	No button pressed.


See Also

MsgBox Function

Visual Basic for Applications Constants


Date Constants

See Also

firstdayofweek Argument Values

Constant	Value	Description

vbUseSystem	0	Use NLS API setting.

vbSunday	1	Sunday

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday

firstweekofyear Argument Values

Constant	Value	Description

vbUseSystem	0	Use application setting if one exists; otherwise use NLS API setting.

vbFirstJan1	1	Start with week in which January 1 occurs (default)

vbFirstFourDays	2	Start with the first week that has at least four days in the new year.

vbFirstFullWeek	3	Start with the first full week of the year.

Return Values

Constant	Value	Description

vbSunday	1	Sunday

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday


See Also

DateDiff Function

DatePart Function

Format Function

Weekday Function

Visual Basic for Applications Constants


Dir, GetAttr, and SetAttr Constants

See Also

Constant	Value	Description

vbNormal	0	Normal (default for Dir and SetAttr).

vbReadOnly	1	Read-only.

vbHidden	2	Hidden.

vbSystem	4	System file.

vbVolume	8	Volume label.

vbDirectory	16	Directory.

vbArchive	32	File has changed since last backup.


See Also

Dir Function

GetAttr Function

SetAttr Statement

Visual Basic for Applications Constants


IMEStatus Constants

See Also

Japanese locale:

Constant	Value	Description

vbIMENoOp	0	No IME installed.

vbIMEOn	1	IME on.

vbIMEOff	2	IME off.

vbIMEDisable	3	IME disabled.

vbIMEHiragana	4	Hiragana double-byte characters (DBC)

vbIMEKatakanaDbl	5	Katakana DBC.

vbIMEKatakanaSng	6	Katakana single-byte characters (SBC).

vbIMEAlphaDbl	7	Alphanumeric DBC.

vbIMEAlphaSng	8	Alphanumeric SBC.

Chinese (traditional and simplified) locale:

Constant	Value	Description

vbIMENoOp	0	No IME installed.

vbIMEOn	1	IME on.

vbIMEOff	2	IME off.

Korean locale [image] examine the first five bits of the return value, which are set as follows:

Bit	Value	Description	Value	Description
0	0	No IME installed.	1	IME installed.
1	0	IME disabled.	1	IME enabled.
2	0	IME English mode.	1	Hangeul mode.
3	0	Banja mode (SB).	1	Junja mode (DB).
4	0	Normal mode.	1	Hanja conversion mode.


See Also

IMEStatus Function

Visual Basic for Applications Constants


Shell Constants

See Also

Constant	Value	Description

vbHide	0	Window is hidden and focus is passed to the hidden window.

vbNormalFocus	1	Window has focus and is restored to its original size and position.

vbMinimizedFocus	2	Window is displayed as an icon with focus.

vbMaximizedFocus	3	Window is maximized with focus.

vbNormalNoFocus	4	Window is restored to its most recent size and position.  The currently active window remains active.

vbMinimizedNoFocus	6	Window is displayed as an icon.  The currently active window remains active.


See Also

Shell Function

Visual Basic for Applications Constants


StrConv Constants

See Also

Constant	Value	Description

vbUpperCase	1	Uppercases the string.

vbLowerCase	2	Lowercases the string.

vbProperCase	3	Uppercases first letter of every word in string.

vbWide*	4*	Converts narrow (single-byte) characters in string to wide (double-byte) characters.

vbNarrow*	8*	Converts wide (double-byte) characters in string to narrow (single-byte) characters.

vbKatakana**	16**	Converts Hiragana characters in string to Katakana characters.

vbHiragana**	32**	Converts Katakana characters in string to Hiragana characters.

vbUnicode***	64***	Converts the string to Unicode using the default code page of the system.

vbFromUnicode***	128***	Converts the string from Unicode to the default code page of the system.

*	Applies to Far East locales.

**	Applies to Japan only.

***	Specifying this bit on 16-bit systems causes a run-time error.


See Also

StrConv Function

Visual Basic for Applications Constants


IMEStatus Function

Returns the current Input Method Editor (IME) mode; available in Far East versions only.

Syntax

IMEStatus

Return Values

Japanese locale:

Constant	Value	Description

vbIMENoOP	0	No IME installed.

vbIMEOn	1	IME on.

vbIMEOff	2	IME off.

vbIMEDisable	3	IME disabled.

vbIMEHiragana	4	Hiragana double-byte characters (DBC).

vbIMEKatakanaDbl	5	Katakana DBC.

vbIMEKatakanaSng	6	Katakana single-byte characters (SBC).

vbIMEAlphaDbl	7	Alphanumeric DBC.

vbIMEAlphaSng	8	Alphanumeric SBC.

Chinese (traditional and simplified) locale:

Constant	Value	Description

vbIMENoOP	0	No IME installed.

vbIMEOn	1	IME on.

vbIMEOff	2	IME off.

Korean locale [image] examine the first five bits of the return, which are set as follows:

Bit	Value	Description	Value	Description
0	0	No IME installed.	1	IME installed.
1	0	IME disabled.	1	IME enabled.
2	0	IME English mode.	1	Hangeul mode.
3	0	Banja mode (SB).	1	Junja mode (DB).
4	0	Normal mode.	1	Hanja conversion mode.


StrConv Function

See Also

Returns a converted string.

Syntax

StrConv(string, conversion)

The StrConv function syntax has these named arguments:

Part	Description

string	The string expression to be converted.

conversion	The sum of values specifying the type of conversion to perform.

Settings

The conversion argument settings are:

Constant	Value	Description

vbUpperCase	1	Converts the string to uppercase characters.

vbLowerCase	2	Converts the string to lowercase characters.

vbProperCase	3	Converts the first letter of every word in string to uppercase.

vbWide*	4*	Converts narrow (single-byte) characters in string to wide (double-byte) characters.

vbNarrow*	8*	Converts wide (double-byte) characters in string to narrow (single-byte) characters.

vbKatakana**	16**	Converts Hiragana characters in string to Katakana characters.

vbHiragana**	32**	Converts Katakana characters in string to Hiragana characters.

vbUnicode***	64***	Converts the string to Unicode using the default code page of the system.

vbFromUnicode***	128***	Converts the string from Unicode to the default code page of the system.

*	Applies to Far East locales.

**	Applies to Japan only.

***	Specifying this bit on 16-bit systems causes a run-time error.

Note   These constants are specified by Visual Basic for applications.  As a result, they can be used anywhere in your code in place of the actual values.  Most can be combined (for example vbUpperCase + vbWide) except when they are mutually exclusive (for example vbUnicode + vbFromUnicode).  The constants vbWide, vbNarrow, vbKatakana, and vbHiragana cause run-time errors when used in locales where they don't apply.

For proper casing the following are valid word separators:  Null (Chr$(0)), horizontal tab (Chr$(9)), linefeed (Chr$(10)), vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (SBCS) (Chr$(32)).  The actual value for a space varies by country for DBCS.


See Also

Chr Function

String Data Type


Document Conventions

Visual Basic documentation uses the following typographic conventions.

Convention	Description

Sub, Font, BackColor, True	Words in bold with initial letter capitalized indicate language-specific keywords.

setup	Words you are instructed to type appear in bold.

object, varname, arglist	Italic, lowercase letters indicate placeholders for information you supply.

pathname, filenumber	Bold, italic, and lowercase letters indicate placeholders for arguments where you can use either positional or named-argument syntax.

[expressionlist]	In syntax, items inside square brackets are optional.

{While | Until}	In syntax, braces and a vertical bar indicate a mandatory choice between two or more items.  You must choose one of the items unless all of the items are also enclosed in square brackets.  For example:

[{This | OrThat}]

VBA.INI, ESC, ENTER	Words in all capital letters indicate filenames, key names, and key sequences.

ALT+F1, CTRL+R	A plus sign (+) between key names indicates a combination of keys.  For example, ALT+F1 means to hold down the ALT key while pressing the F1 key.

MyString = "Hello, world!"	This font is used for code, variables, and error message text.

' This is a comment.	An apostrophe (') introduces code comments.

MyVar = "This is an " _	A space and an underscore (_) continues a line of code.

& "example" _

& " of how to continue code."


Collection Object Methods (Object Browser)

See Also

The Collection object module displays procedures used to perform collection operations.

To get Help on a particular method

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


See Also

Collection Object


Constants (Object Browser)

See Also

The Constants module in the Visual Basic for applications object library displays the predefined constants used with the Dir, GetAttr, IMEStatus, MsgBox, StrConv, and VarType functions and with the SetAttr statement.


See Also

Dir Function

GetAttr Function

IMEStatus Function

MsgBox Function

SetAttr Statement

StrConv Function

VarType Function

Visual Basic for Applications Constants


Conversion Procedures (Object Browser)

See Also

The Conversion module displays the procedures used to perform conversion operations.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.

Note   When you use Variant variables, explicit data-type conversions are unnecessary.


See Also

Conversion Keyword Summary

Variant Data Type


DateTime Procedures (Object Browser)

See Also

The DateTime module displays the procedures used to perform date and time operations.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


See Also

Dates and Times Keyword Summary


FileSystem Procedures (Object Browser)

See Also

The FileSystem module displays the procedures used to perform file or directory and system operations.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


See Also

Directories and Files Keyword Summary


Financial Procedures (Object Browser)

See Also

The Financial module displays procedures used to perform financial operations.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


See Also

Financial Keyword Summary


Information Procedures (Object Browser)

The Information module displays the procedures used to return, test for, or verify information.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


Interaction Procedures (Object Browser)

The Interaction module displays procedures used to interact with objects, applications, and systems.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


Math Procedures (Object Browser)

See Also

The Math module displays procedures used to perform mathematical operations.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


See Also

Math Keyword Summary


String Procedures (Object Browser)

See Also

The String module displays procedures used to perform string operations.

To get Help on a particular procedure

1.	Select the procedure from the Methods/Properties list box.

2.	Choose the [image] button.


See Also

String Manipulation Keyword Summary


AppActivate Statement

See Also	Example

Activates an application window.

Syntax

AppActivate title[, wait]

The AppActivate statement syntax has these named arguments:

Part	Description

title	The title argument is the string expression in the title bar of the application window you want to activate.

In addition, the task ID returned by the Shell function can be used, in place of title, to activate an application.

wait	Boolean value specifying whether the calling application has the focus before activating another.  If False (default), the specified application is immediately activated, even if the calling application does not have the focus.  If True, the calling application waits until it has the focus, then activates the specified application.

Remarks

The AppActivate statement changes the focus to the named application or window but does not affect whether it is maximized or minimized.  Focus moves from the activated application window when the user takes some action to change the focus or close the window.  Use the Shell function to start an application and set the window style.

In determining which application to activate, title is compared to the title string of each running application.  If there is no exact match, any application whose title string begins with title is activated.  If there is more than one instance of the application named by title, one is arbitrarily activated.


 See Also

Shell Function

SendKeys Statement


Beep Statement

Example

Sounds a tone through the computer's speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depend on your hardware and system software and vary among computers.


InputBox Function

See Also	Example

Displays a prompt in a dialog box, waits 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][, helpfile, context])

The InputBox function syntax has these named arguments:

Part	Description

prompt	String expression displayed as the message in the dialog box.  The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.  If prompt consists of more than one line, you can separate the lines using either a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return-linefeed character combination (Chr(13) & Chr(10)) between each line.

title	String expression displayed in the title bar of the dialog box.  If you omit title, the application name is placed in the title bar.

default	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 xpos is omitted, the dialog box is horizontally centered.

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 ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.

helpfile	String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is provided, context must also be provided.

context	Numeric expression that is the Help context number the Help author assigned to the appropriate Help topic.  If context is provided, helpfile must also be provided.

Remarks

When both helpfile and context are supplied, a Help button is automatically added to the dialog box.

If the user chooses OK or presses ENTER, the InputBox function returns whatever is in the text box.  If the user chooses Cancel, the function returns a zero-length string ("").

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


 See Also

MsgBox Function

Returning Strings From Functions


MsgBox Function

See Also	Example

Displays a message in a dialog box, waits for the user to choose a button, and returns a value indicating which button the user has chosen.

Syntax

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

The MsgBox function syntax has these named arguments:

Part	Description

prompt	String expression displayed as the message in the dialog box.  The maximum length of prompt is approximately 1024 characters, depending on the width of the characters used.  If prompt consists of more than one line, you can separate the lines using either a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return-linefeed character combination (Chr(13) & Chr(10)) between each line.

buttons	Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box.  If omitted, the default value for buttons is 0.

title	String expression displayed in the title bar of the dialog box.  If you omit title, the application name is placed in the title bar.

helpfile	String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box.  If helpfile is provided, context must also be provided.

context	Numeric expression that is the Help context number the Help author assigned to the appropriate Help topic.  If context is provided, helpfile must also be provided.

Settings

The buttons argument settings are:

Constant	Value	Description

vbOKOnly	0	Display OK button only.

vbOKCancel	1	Display OK and Cancel buttons.

vbAbortRetryIgnore	2	Display Abort, Retry, and Ignore buttons.

vbYesNoCancel	3	Display Yes, No, and Cancel buttons.

vbYesNo	4	Display Yes and No buttons.

vbRetryCancel	5	Display Retry and Cancel buttons.

vbCritical	16	Display Critical Message icon.

vbQuestion	32	Display Warning Query icon.

vbExclamation	48	Display Warning Message icon.

vbInformation	64	Display Information Message icon.

vbDefaultButton1	0	First button is default.

vbDefaultButton2	256	Second button is default.

vbDefaultButton3	512	Third button is default.

vbApplicationModal	0	Application modal; the user must respond to the message box before continuing work in the current application.

vbSystemModal	4096	System modal; all applications are suspended until the user responds to the message box.

The first group of values (0 [image] 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 buttons, use only one number from each group.

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

Return Values

Constant	Value	Button chosen

vbOK	1	OK

vbCancel	2	Cancel

vbAbort	3	Abort

vbRetry	4	Retry

vbIgnore	5	Ignore

vbYes	6	Yes

vbNo	7	No

Remarks

When both helpfile and context are provided, the user can press F1 to view the Help topic corresponding to the context.

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

Note   If you want to specify more than the first named argument, you must use MsgBox in an expression.  If you want to omit some positional arguments, you must include the corresponding comma delimiter.


 See Also

InputBox Function

Returning Strings From Functions


RGB Function

See Also	Example

Returns a whole number representing an RGB color value.

Syntax

RGB (red, green, blue)

The RGB function syntax has these named arguments:

Part	Description

red	Number in the range 0 to 255, inclusive, that represents the red component of the color.

green	Number in the range 0 to 255, inclusive, that represents the green component of the color.

blue	Number in the range 0 to 255, inclusive, that represents the blue component of the color.

Remarks

Application methods and properties that accept a color specification expect that specification to be a number representing an RGB color value.  An RGB color value specifies the relative intensity of red, green, and blue to cause a specific color to be displayed.

The value for any argument to RGB that exceeds 255 is assumed to be 255.

The following table lists some standard colors and the red, green, and blue values they include:

Color	Red Value	Green Value	Blue Value

Black	0	0	0

Blue	0	0	255

Green	0	255	0

Cyan	0	255	255

Red	255	0	0

Magenta	255	0	255

Yellow	255	255	0

White	255	255	255


 See Also

QBColor Function


SendKeys Statement

See Also	Example

Sends one or more keystrokes to the active window as if typed at the keyboard.

Syntax

SendKeys string[, wait]

The SendKeys statement syntax has these named arguments :

Part	Description

string	String expression specifying the keystroke(s) to send.

wait	Boolean value specifying the wait mode.  If False (default), control is returned to the procedure immediately after the keys are sent.  If True, keystrokes must be processed before control is returned to the procedure.

Remarks

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 string.  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 string.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys.  To specify one of these characters, enclose it within 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, brackets do have a 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

BACKSPACE	{BACKSPACE}, {BS}, or {BKSP}

BREAK	{BREAK}

CAPS LOCK	{CAPSLOCK}

DEL	{DELETE} or {DEL}

DOWN ARROW	{DOWN}

END	{END}

ENTER	{ENTER} or ~

ESC	{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 the SHIFT, CTRL, and ALT keys, precede the regular key code with one or more of the following codes:

Key	Code

SHIFT	+

CTRL (CONTROL)	^

ALT	%

To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses.  For example, to specify to hold down SHIFT while E and C are pressed, use "+(EC)".  To specify to hold down SHIFT while E is pressed, followed by C 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

AppActivate Statement

DoEvents Function


Operator Summary

See Also

Arithmetic Operators

Operators used to perform mathematical calculations.

Comparison Operators

Operators used to perform comparisons.

Concatenation Operators

Operators used to combine strings.

Logical Operators

Operators used to perform logical operations.


See Also

Operator Precedence


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.  Comparison operators all have equal precedence; that is, they are evaluated in the left to right order in which they appear.  Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic	Comparison	Logical

Exponentiation (^)	Equality (=)	Not

Negation (-)'	Inequality (<>)	And

Multiplication and division (*,/)	Less than (<)	Or

Integer division (\)	Greater than (>)	Xor

Modulo arithmetic (Mod)	Less than or Equal to (<=)	Eqv

Addition and subtraction (+,-)	Greater than or Equal to (>=)	Imp

String concatenation (&)	Like

Is

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 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.  The Is operator is an object reference comparison operator.  It does not compare objects or their values; it checks only to determine if two object references refer to the same object.


 See Also

Is Operator

Like Operator

Operator Summary


Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator


Concatenation Operators

& Operator

+ 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

The ^ operator syntax has these parts:

Part	Description

result	Any numeric variable.

number	Any numeric expression.

exponent	Any numeric expression.

Remarks

Number can be negative only if exponent is an integer value.  When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or a Variant containing a Double.  However, if either number or exponent is a Null expression, result is also Null.


 See Also

Arithmetic Operators

Operator Precedence

Operator Summary


+ Operator

See Also	Example

Used to sum two numbers.

Syntax

result = expression1+expression2

The + operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

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 will occur.  If at least one expression is not a Variant, the following rules apply:

If	Then
Both expressions are numeric data types (Byte, Boolean, Integer, Long, Single, Double, Date, or Currency)	Add.
Both expressions are String	Concatenate.
One expression is a numeric data type and the other is any Variant (except Null)	Add.
One expression is a String and the other is any Variant (except Null)	Concatenate.
One expression is an Empty Variant	Return the remaining expression unchanged as result.
One expression is a numeric data type and the other is a String	A Type mismatch error occurs.
Either expression is Null	result is Null.
If both expressions are Variant expressions, the underlying type of the expressions determines the behavior of the + operator in the following way:

If	Then
Both Variant expressions are numeric	Add.
Both Variant expressions are strings	Concatenate.
One Variant expression is numeric and the other is a string	Add.
For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression.  The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, and 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 Long, Single, or Date variant that overflows its legal range, result is converted to a Double variant.

When the data type of result is a Byte variant that overflows its legal range, result is converted to an Integer variant.

When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

When a Date is added to any data type, the data type of result is always a Date.

Note   The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

If one or both expressions are Null expressions, result is Null.  If both expressions are Empty, result is an Integer.  However, if only one expression is Empty, the other expression is returned unchanged as result.


 See Also

Arithmetic Operators

Concatenation Operators

Operator Precedence

Operator Summary


- Operator

See Also	Example

Used to find the difference between two numbers or to indicate the negative value of a numeric expression.

Syntax 1

result = number1-number2

Syntax 2

-number

The - operator syntax has these parts:

Part	Description

result	Any numeric variable.

number	Any numeric expression.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers.  In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an expression.

The data type of result is usually the same as that of the most precise expression.  The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, Currency.  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 Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.

When the data type of result is a Byte variant that overflows its legal range, result is converted to an Integer variant.

When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

When subtraction involves a Date and any other data type, the data type of result is a Date.

When subtraction involves two Date expressions, the data type of result is Double.

Note   The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

If one or both expressions are Null expressions, result is Null.  If an expression is Empty, it is treated as if it were 0.


 See Also

Arithmetic Operators

Operator Precedence

Operator Summary


* Operator

See Also	Example

Used to multiply two numbers.

Syntax

result = number1*number2

The * operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

The data type of result is usually the same as that of the most precise expression.  The order of precision, from least to most precise, is Byte, Integer, Long, Single, Currency, Double.  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 Long, Single, or Date variant that overflows its legal range, result is converted to a Variant containing a Double.

When the data type of result is a Byte variant that overflows its legal range, result is converted to an Integer variant.

When the data type of result is an Integer variant that overflows its legal range, result is converted to a Long variant.

Note   The order of precision used by multiplication is not the same as the order of precision used by addition and subtraction.

If one or both expressions are Null expressions, result is Null.  If an expression is Empty, it is treated as if it were 0.


 See Also

Arithmetic Operators

Operator Precedence

Operator Summary


/ Operator

See Also	Example

Used to divide two numbers and return a floating-point result.

Syntax

result = number1/number2

The / operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

The data type of result is usually a Double or a Double variant.  The following are exceptions to this rule:

When both expressions are Byte, Integer, or Single expressions, result is a Single unless it overflows its legal range; in which case, an error occurs.

When both expressions are Byte, Integer, or Single variants, result is a Single variant unless it overflows its legal range; in which case, result is a Variant containing a Double.

If one or both expressions are Null expressions, result is Null.  Any expression that is Empty is treated as 0.


 See Also

Arithmetic Operators

Operator Precedence

Operator Summary


\ Operator

See Also	Example

Used to divide two numbers and return an integer result.

Syntax

result = number1\number2

The \ operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

Before division is performed, the numeric expressions are rounded to Byte, Integer, or Long expressions.

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Long variant, regardless of whether result is a whole number.  Any fractional portion is truncated.  However, if any expression is Null, result is also Null.  Any expression that is Empty is treated as 0.


 See Also

Arithmetic Operators

Operator Precedence

Operator Summary


Mod Operator

See Also	Example

Used to divide two numbers and return only the remainder.

Syntax

result = number1 Mod number2

The Mod operator syntax has these parts:

Part	Description

result	Any numeric variable.

number1	Any numeric expression.

number2	Any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result.  For example, in the following expression, A (which is result) equals 5.

A = 19 Mod 6.7

Usually, the data type of result is a Byte, Byte variant, Integer, Integer variant, Long, or Variant containing a Long, regardless of whether or not result is a whole number.  Any fractional portion is truncated.  However, if any expression is Null, result is also Null.  Any expression that is Empty is treated as 0.


 See Also

Arithmetic Operators

Operator Precedence

Operator Summary


& Operator

See Also	Example

Used to force string concatenation of two expressions.

Syntax

result = expression1 & expression2

The & operator syntax has these parts:

Part	Description

result	Any String or Variant variable.

expression1	Any expression.

expression2	Any expression.

Remarks

Whenever an expression is not a string, it is converted to a String variant.  The data type of result is String if both expressions are String expressions; otherwise, result is a String variant.  If both expressions are Null, result is also Null.  However, if only one expression is Null, that expression is treated as a zero-length string when concatenated with the other expression.  Any expression that is Empty is also treated as a zero-length string.


 See Also

Concatenation Operators

Operator Precedence

Operator Summary


Comparison Operators

See Also	Example

Used to compare expressions.

Syntax

result = expression1 comparisonoperator expression2

result = object1 Is object2

result = string Like pattern

Comparison operators have these parts:

Part	Description

result	Any numeric variable.

expression	Any expression.

comparisonoperator	Any comparison operator.

object	Any object name.

string	Any string expression.

pattern	Any string expression or range of characters.

Remarks

The Is and Like operators have specific comparison functionality that differs from the operators in the following table.  The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator	Description	True if	False if	Null if
<	Less than	expression1 < expression2	expression1 >= expression2	expression1 or expression2 = Null
<=	Less than or equal to	expression1 <= expression2	expression1 > expression2	expression1 or expression2 = Null
>	Greater than	expression1 > expression2	expression1 <= expression2	expression1 or expression2 = Null
>=	Greater than or equal to	expression1 >= expression2	expression1 < expression2	expression1 or expression2 = Null
=	Equal to	expression1 = expression2	expression1 <> expression2	expression1 or expression2 = Null
<>	Not equal to	expression1 <> expression2	expression1 = expression2	expression1 or expression2 = 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 (Byte, Boolean, Integer, Long, Single, Double, Date, 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 that is, or can be, a number	Perform a numeric comparison.
One expression is a numeric data type and the other is a string Variant that can't be converted to a number	A Type Mismatch error occurs.
One expression is a String and the other is any Variant (except a 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.
If expression1 and expression2 are both Variant expressions, their underlying type determines how they are compared.  The following table shows how the expressions are compared or what results from the comparison, depending on the underlying type of the Variant:

If	Then
Both Variant expressions are numeric	Perform a numeric comparison.
Both Variant expressions are strings	Perform a string comparison.
One Variant expression is numeric and the other is a string	The numeric expression is less than the string expression.
One Variant expression is Empty and the other is numeric	Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is a 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.  When a Single is compared to a Double, the Double is rounded to the precision of the Single.


 See Also

Is Operator

Like Operator

Operator Precedence

Operator Summary

Option Compare Statement


And Operator

See Also	Example

Used to perform a logical conjunction on two expressions.

Syntax

result = expression1 And expression2

The And operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If, and only if, both expressions evaluate to True, result is True.  If either expression evaluates to False, result is False.  The following table illustrates how result is determined:

If expression1 is	And expression2 is	The result is

True	True	True

True	False	False

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 expression1 is	And bit in expression2 is	The result is

0	0	0

0	1	0

1	0	0

1	1	1


 See Also

Logical Operators

Operator Precedence

Operator Summary


Eqv Operator

See Also	Example

Used to perform a logical equivalence on two expressions.

Syntax

result = expression1 Eqv expression2

The Eqv operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If either expression is Null, result is also Null.  When neither expression is Null, result is determined according to the following table:

If expression1 is	And expression2 is	The result 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 expression1 is	And bit in expression2 is	The result is

0	0	1

0	1	0

1	0	0

1	1	1


 See Also

Logical Operators

Operator Precedence

Operator Summary


Imp Operator

See Also	Example

Used to perform a logical implication on two expressions.

Syntax

result = expression1 Imp expression2

The Imp operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

The following table illustrates how result is determined:

If expression1 is	And expression2 is	The result 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 expression1 is	And bit in expression2 is	The result is

0	0	1

0	1	1

1	0	0

1	1	1


 See Also

Logical Operators

Operator Precedence

Operator Summary


Not Operator

See Also	Example

Used to perform logical negation on an expression.

Syntax

result = Not expression

The Not operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression	Any expression.

Remarks

The following table illustrates how result is determined:

If expression 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 expression	Bit in result

0	1

1	0


 See Also

Logical Operators

Operator Precedence

Operator Summary


Or Operator

See Also	Example

Used to perform a logical disjunction on two expressions.

Syntax

result = expression1 Or expression2

The Or operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If either or both expressions evaluate to True, result is True.  The following table illustrates how result is determined:

If expression1 is	And expression2 is	The result 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 expression1 is	And bit in expression2 is	The result is

0	0	0

0	1	1

1	0	1

1	1	1


 See Also

Logical Operators

Operator Precedence

Operator Summary


Xor Operator

See Also	Example

Used to perform a logical exclusion on two expressions.

Syntax

result = expression1 Xor expression2

The Xor operator syntax has these parts:

Part	Description

result	Any numeric variable.

expression1	Any expression.

expression2	Any expression.

Remarks

If one, and only one, of the expressions evaluates to True, result is True.  However, if either expression is Null, result is also Null.  When neither expression is Null, result is determined according to the following table:

If expression1 is	And expression2 is	The result 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 expression1 is	And bit in expression2 is	The result is

0	0	0

0	1	1

1	0	1

1	1	0


 See Also

Logical Operators

Operator Precedence

Operator Summary


Like Operator

See Also	Example

Used to compare two strings.

Syntax

result = string Like pattern

The Like operator syntax has these parts:

Part	Description

result	Any numeric variable.

string	Any string expression.

pattern	Any string expression conforming to the pattern-matching conventions described in Remarks.

Remarks

If string matches pattern, result is True; if there is no match, result is False; and if either string or pattern is Null, result is also Null.

The behavior of the Like operator depends on the Option Compare statement.  Unless otherwise specified, the default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters.  Sort order is determined by the code page.  In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive textual sort order determined by your system's locale. The same characters shown above, when sorted using Option Compare Text, produce the following text sort order:

(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons.  The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings.  The following table shows the characters allowed in pattern and what they match:

Character(s) in pattern	Matches in string

?	Any single character.

*	Zero or more characters.

#	Any single digit (0 [image] 9).

[charlist]	Any single character in charlist.

[!charlist]	Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note   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 (]) can't 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 string contains any of the uppercase letters in the range A through Z.  Multiple ranges are included within the brackets without any delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on).  Using the same example shown above with Option Compare Binary, the range [A [image] E] matches A, B and E.  With Option Compare Text, [A [image] E] matches A, a, À, à, B, b, E, e.  Note that it does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

An exclamation point (!) at the beginning of charlist means that a match is made if any character except the ones in charlist is found in string.  When used outside brackets, the exclamation point matches itself.

The hyphen (-) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself.  In any other location, the hyphen is used to identify a range of characters.

When a range of characters is specified, they must appear in ascending sort order (from lowest to highest).  [A-Z] is a valid pattern, but [Z-A] is not.

The character sequence [] is ignored; it is considered 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 system locale settings, an occurrence of the single special character in either pattern or string matches the equivalent 2-character sequence in the other string.  Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2-character sequence in string.


 See Also

Comparison Operators

Instr Function

Operator Precedence

Operator Summary

Option Compare Statement

StrComp Function


Is Operator

See Also	Example

Used to compare two object reference variables.

Syntax

result = object1 Is object2

The Is operator syntax has these parts:

Part	Description

result	Any numeric variable.

object1	Any object name.

object2	Any object name.

Remarks

If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

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

Comparison Operators

Operator Precedence

Operator Summary

Set Statement


Chr Function

See Also	Example

Returns the character associated with the specified character code.

Syntax

Chr(charcode)

The charcode argument is a number that identifies a character.

Remarks

Numbers from 0 to 31 are the same as standard, nonprintable ASCII codes.  For example, Chr(10) returns a linefeed character.

Note   Another function (ChrB) is provided for use with byte data contained in a string.  Instead of returning a character, which may be one or two bytes, ChrB always returns a single byte.


See Also

Asc Function

Character Set

Returning Strings From Functions

Str Function


Format Function

See Also	Example

Formats an expression according to instructions contained in a format expression.

Syntax

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

The Format function syntax has these parts:

Part	Description

expression	Any valid expression.

format	A valid named or user-defined format expression.

firstdayofweek	A constant that specifies the first day of the week, as described in Settings.

firstweekofyear	A constant that specifies the first week of the year, as described in Settings.

Settings

The firstdayofweek argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use NLS API setting.

vbSunday	1	Sunday (default)

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday

The firstweekofyear argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use NLS API setting.

vbFirstJan1	1	Start with week in which January 1 occurs (default).

vbFirstFourDays	2	Start with the first week that has at least four days in the year.

vbFirstFullWeek	3	Start with the first full week of the year.

Remarks

To Format	Do This

Numbers	Use predefined named numeric formats or create user-defined numeric formats.

Dates and times	Use predefined named date/time formats or create user-defined date/time formats.

Date and time serial numbers	Use date and time formats or numeric formats.

Strings	Create your own user-defined string formats.

If you try to format a number without specifying format, Format provides the same functionality as the Str function.  However, positive numbers formatted as strings using Format lack the leading space reserved for displaying the sign of the value; whereas, those converted using Str retain the leading space.


See Also

Different Formats for Different Numeric Values

Different Formats for Different String Values

Named Date/Time Formats

Named Numeric Formats

Returning Strings From Functions

Str Function

User-Defined Date/Time Formats

User-Defined Numeric Formats

User-Defined String Formats


Named Numeric Formats (Format Function)

See Also

The following table identifies the predefined numeric format names:

Format name	Description

General Number	Display number as is, with no thousand separators.

Currency	Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator.  Note that output is based on system locale settings.

Fixed	Display at least one digit to the left and two digits to the right of the decimal separator.

Standard	Display number with thousands separator, at least one digit to the left and two digits to the right of the decimal separator.

Percent	Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.

Scientific	Use standard scientific notation.

Yes/No	Display No if number is 0; otherwise, display Yes.

True/False	Display False if number is 0; otherwise, display True.

On/Off	Display Off if number is 0; otherwise, display On.


See Also

Format Function

Named Date/Time Formats


User-Defined Numeric Formats (Format Function)

See Also	Example

The following table identifies characters you can use to create user-defined number formats:

Character	Description

None	No formatting

Display the number with no formatting.

0	Digit placeholder

Display a digit or a zero.  If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros.  If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros.  If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.

#	Digit placeholder

Display a digit or nothing.  If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

.	Decimal placeholder

In some locales, a comma is used as the decimal separator.  The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator.  If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator.  If you always want a leading zero 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 recognized by your system.

%	Percentage placeholder

The expression is multiplied by 100.  The percent character (%) is inserted in the position where it appears in the format string.

,	Thousand separator

In some locales, a period is used as a thousand separator.  The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator.  Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #).  Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means "scale the number by dividing it by 1000, rounding as needed."  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 thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator.  The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.

:	Time separator

In some locales, other characters may be used to represent the time separator.  The time separator separates hours, minutes, and seconds when time values are formatted.  The actual character used as the time separator in formatted output is determined by your system settings.

/	Date separator

In some locales, other characters may be used to represent the date separator.  The date separator separates the day, month, and year when date values are formatted.  The actual character used as the date separator in formatted output is determined by your system settings.

E- E+ e- e+	Scientific format

If the format expression contains at least one digit placeholder (0 or #) to the 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.

- + $ ( ) 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 format from within code, you must use Chr(34) to enclose the text (34 is the character code for a double quotation mark).


See Also

Different Formats for Different Numeric Values

Format Function

User-Defined Date/Time Formats

User-Defined String Formats


Different Formats for Different Numeric Values (Format Function)

See Also

A user-defined format expression for numbers can have from one to four sections separated by semicolons.  (If the format argument contains one of the named numeric formats, only one section is allowed.)

If you use	The result is

One section only	The format expression applies to all values.

Two sections	The first section applies to positive values and zeros, the second to negative values.

Three sections	The first section applies to positive values, the second to negative values, and the third to zeros.

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"


See Also

Different Formats for Different String Values

Format Function


User-Defined Numeric Format Examples

Some sample format expressions for numbers are shown below. (These examples all assume that your system's locale setting is English-U.S.)  The first column contains the format strings.  The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (format)	Positive 5	Negative 5	Decimal .5	Null

Zero-length string	5	-5	0.5

0	5	-5	1

0.00	5.00	-5.00	0.50

#,##0	5	-5	1

#,##0.00;;;Nil	5.00	-5.00	0.50	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


Named Date/Time Formats (Format Function)

See Also

The following table identifies the predefined date and time format names:

Format Name	Description

General Date	Display a date and/or time.  For real numbers, display a date and time (for example, 4/3/93 05:34 PM); if there is no fractional part, display only a date (for example, 4/3/93); if there is no integer part, display time only (for example, 05:34 PM).  Date display is determined by your system settings.

Long Date	Display a date according to your system's long date format.

Medium Date	Display a date using the medium date format appropriate for the language version of Visual Basic.

Short Date	Display a date using your system's short date format.

Long Time	Display a time using your system's long time format: includes hours, minutes, seconds.

Medium Time	Display time in 12-hour format using hours and minutes and the AM/PM designator.

Short Time	Display a time using the 24-hour format (for example, 17:45).


See Also

Format Function

Named Numeric Formats


User-Defined Date/Time Formats (Format Function)

See Also	Example

The following table identifies characters you can use to create user-defined date/time formats:

Character	Description

:	Time separator.  In some locales, other characters may be used to represent the time separator.  The time separator separates hours, minutes, and seconds when time values are formatted.  The actual character used as the time separator in formatted output is determined by your system settings.

/	Date separator.  In some locales, other characters may be used to represent the date separator.  The date separator separates the day, month, and year when date values are formatted.  The actual character used as the date separator in formatted output is determined by your system settings.

c	Display the date as ddddd and display the time as t t t t t, in that order.  Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.

d	Display the day as a number without a leading zero (1 [image] 31).

dd	Display the day as a number with a leading zero (01 [image] 31).

ddd	Display the day as an abbreviation (Sun [image] Sat).

dddd	Display the day as a full name (Sunday [image] Saturday).

ddddd	Display the date as a complete date (including day, month, and year), formatted according to your system's short date format setting.  The default short date format is m/d/yy.

dddddd	Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system.  The default long date format is mmmm dd, yyyy.

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 [image] 53).

m	Display the month as a number without a leading zero (1 [image] 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 [image] 12).  If m immediately follows h or hh, the minute rather than the month is displayed.

mmm	Display the month as an abbreviation (Jan [image] Dec).

mmmm	Display the month as a full month name (January [image] December).

q	Display the quarter of the year as a number (1 [image] 4).

y	Display the day of the year as a number (1 [image] 366).

yy	Display the year as a 2-digit number (00 [image] 99).

yyyy	Display the year as a 4-digit number (100 [image] 9999).

h	Display the hour as a number without leading zeros (0 [image] 23).

hh	Display the hour as a number with leading zeros (00 [image] 23).

n	Display the minute as a number without leading zeros (0 [image] 59).

nn	Display the minute as a number with leading zeros (00 [image] 59).

s	Display the second as a number without leading zeros (0 [image] 59).

ss	Display the second as a number with leading zeros (00 [image] 59).

t t t t t	Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system.  A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M.  The default time format is h:mm:ss.

AM/PM	Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.

am/pm	Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.

A/P	Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.

a/p	Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.

AMPM	Use the 12-hour clock and display the AM string literal as defined by your system with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M.  AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings.  The default format is AM/PM.


See Also

Format Function

User-Defined Numeric Formats

User-Defined String Formats


User-Defined Date/Time Format Examples

The following are examples of user-defined date and time formats for December 7, 1958:

Format	Display

m/d/yy	12/7/58

d-mmm	7-Dec

d-mmmm-yy	7-December-58

d mmmm	7 December

mmmm yy	December 58

hh:mm AM/PM	08:50 PM

h:mm:ss a/p	8:50:35 p

h:mm	20:50

h:mm:ss	20:50:35

m/d/yy h:mm	12/7/58 20:50


User-Defined String Formats (Format Function)

See Also

You can use any of the following characters to create a format expression for strings:

Character	Description

@	Character placeholder

Display a character or a space.  If the string has a character in the position where the @ 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 the string has a character 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

Display all characters in lowercase format.

>	Force uppercase

Display all characters in uppercase format.

!	Force left to right fill of placeholders

The default is to fill from right to left.


See Also

Different Formats for Different String Values

Format Function

User-Defined Date/Time Formats

User-Defined Numeric Formats


Different Formats for Different String Values (Format Function)

See Also

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.


See Also

Different Formats for Different Numeric Values

Format Function


Hex Function

See Also	Example

Returns a string representing the hexadecimal value of a number.

Syntax

Hex(number)

The number argument is any valid numeric or string expression.

Remarks

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

If number is	Hex returns

Null	Null.

Empty	Zero (0).

Any other number	Up to eight hexadecimal characters.

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


See Also

Oct Function

Returning Strings From Functions


InStr Function

See Also	Example

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

Syntax

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

The InStr function syntax has these named arguments:

Part	Description

start	Numeric expression that sets the starting position for each search.  If omitted, search begins at the first character position.  If start contains Null, an error occurs.  The start argument is required if compare is specified.

string1	String expression being searched.

string2	String expression sought.

compare	Specifies the type of string comparison.  The compare argument can be omitted, it can be 0 or 1, or it can be the value of the CollatingOrder property of a Field object.  Specify 0 (default) to perform a binary comparison.  Specify 1 to perform a textual, case-insensitive comparison.  Specify the return value of the CollatingOrder property of a Field object if you want to sort or compare values from a database in the same way the database itself would.  If compare is Null, an error occurs.  The start argument is required if compare is specified.  If compare is omitted, the Option Compare setting determines the type of comparison.

Return Values

If	InStr returns

string1 is zero-length	0

string1 is Null	Null

string2 is zero-length	start

string2 is Null	Null

string2 is not found	0

string2 is found within string1 	Position at which match is found

start > string2	0

Remarks

Note   Another function (InStrB) is provided for use with byte data contained in a string.  Instead of returning the character position of the first occurrence of one string within another, InStrB returns the byte position.


See Also

Option Compare Statement

STRComp Function


LCase Function

See Also	Example

Returns a string that has been converted to lowercase.

Syntax

LCase(string)

The string argument is any valid string expression.  If string contains Null, Null is returned.

Remarks

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


See Also

Returning Strings From Functions

UCase Function


Left Function

See Also	Example

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

Syntax

Left(string, length)

The Left function syntax has these named arguments:

Part	Description

string	String expression from which the leftmost characters are returned.  If string contains Null, Null is returned.

length	Numeric expression indicating how many characters to return.  If 0, a zero-length string is returned.  If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

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

Note   Another function (LeftB) is provided for use with byte data contained in a string.  Instead of specifying the number of characters to return, length specifies the number of bytes.


See Also

Len Function

Mid Function

Returning Strings From Functions

Right Function


Len Function

See Also	Example

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

Syntax

Len(string | varname)

The Len function syntax has these parts:

Part	Description

string	Any valid string expression.  If string contains Null, Null is returned.

varname	Any valid variable name.  If varname contains Null, Null is returned.  If varname is a Variant, Len treats it the same as a String and always returns the number of characters it contains.

Caution   Len may not be able to determine the actual number of storage bytes required when used with user-defined data types.

Note   Another function (LenB) is provided for use with byte data contained in a string.  Instead of returning the number of characters in a string, LenB returns the number of bytes used to represent that string.


See Also

Data Type Summary

InStr Function


LSet Statement

See Also	Example

Left aligns a string within a string variable, or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax

LSet stringvar = string

LSet varname1 = varname2

The LSet statement syntax has these parts:

Part	Description

stringvar	Name of string variable.

string	String expression to be left-aligned within stringvar.

varname1	Variable name of the user-defined type being copied to.

varname2	Variable name of the user-defined type being copied from.

Remarks

LSet replaces any leftover characters in stringvar with spaces.

If string is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.

Warning   Using LSet to copy a variable of one user-defined type into a variable of a different user-defined type is not recommended and should not be done without understanding that copying data of one data type into space reserved for a different data type can cause unpredictable results.

When you copy a variable from one user-defined type to another, the binary data from one variable is simply copied into the memory space of the other, without regard for the data types specified for the elements contained within.


See Also

RSet Statement


LTrim, RTrim, and Trim Functions

See Also	Example

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

Syntax

LTrim(string)

RTrim(string)

Trim(string)

The string argument is any valid string expression.  If string contains Null, Null is returned.


See Also

Left Function

Returning Strings From Functions

Right Function


Mid Function

See Also	Example

Returns a specified number of characters from a string.

Syntax

Mid(string, start[, length])

The Mid function syntax has these named arguments:

Part	Description

string	String expression from which characters are returned.  If string contains Null, Null is returned.

start	Character position in string at which the part to be taken begins.  If start is greater than the number of characters in string, Mid returns a zero-length string.

length	Number of characters to return.  If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

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

Note   Another function (MidB) is provided for use with byte data contained in a string.  Instead of specifying the number of characters, the arguments  specify numbers of bytes.


See Also

Left Function

Len Function

LTrim Function

Mid Statement

Returning Strings From Functions

Right Function

RTrim Function

Trim Function


Mid Statement

See Also	Example

Replaces a specified number of characters in a string variable with characters from another string.

Syntax

Mid(stringvar, start[, length]) = string

The Mid statement syntax has these parts:

Part	Description

stringvar	Name of string variable to modify.

start	Character position in stringvar where the replacement of text begins.

length	Number of characters to replace.  If omitted, all of string is used.

string	String expression that replaces part of stringvar.

Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.

Note   Another statement (MidB) is provided for use with byte data contained in a string.  In the MidB statement, start specifies the byte position within stringvar where replacement begins and length specifies the numbers of bytes to replace.


See Also

Mid Function


Oct Function

See Also	Example

Returns a string representing the octal value of a number.

Syntax

Oct(number)

The number argument is any valid numeric or string expression.

Remarks

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

If number is	Oct returns

Null	Null.

Empty	Zero (0).

Any other number	Up to 11 octal characters.

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


See Also

Hex Function

Returning Strings From Functions


Right Function

See Also	Example

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

Syntax

Right(string, length)

The Right function syntax has these named arguments:

Part	Description

string	String expression from which the rightmost characters are returned.  If string contains Null, Null is returned.

length	Numeric expression indicating how many characters to return.  If 0, a zero-length string is returned.  If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

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

Note   Another function (RightB) is provided for use with byte data contained within a string.  Instead of specifying the number of characters to return, length specifies the number of bytes.


See Also

Left Function

Len Function

Mid Function

Returning Strings From Functions


RSet Statement

See Also	Example

Right aligns a string within a string variable.

Syntax

RSet stringvar = string

The RSet statement syntax has these parts:

Part	Description

stringvar	Name of string variable.

string	String expression to be right-aligned within stringvar.

Remarks

RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

RSet can't be used with user-defined types.


See Also

LSet Statement


Space Function

See Also	Example

Returns a string consisting of the specified number of spaces.

Syntax

Space(number)

The number argument is the number of spaces you want in the string.

Remarks

The Space function is useful for formatting output and clearing data in fixed-length strings.


See Also

Returning Strings From Functions

Spc Function

String Function


Str Function

See Also	Example

Returns a string representation of a number.

Syntax

Str(number)

The number argument is any valid numeric expression.

Remarks

When numbers are converted to strings, a leading space is always reserved for the sign of number.  If number is positive, the returned string contains a leading space and the plus sign is implied.

Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats.  Unlike Str, the Format function doesn't include a leading space for the sign of number.

Note   The Str function recognizes only the period (.) as a valid decimal separator.  When a possibility exists that different decimal separators may be used (for example, in international applications), you should use CStr to convert a number to a string.


See Also

CStr Function

Format Function

Returning Strings From Functions

Val Function


StrComp Function

See Also	Example

Returns a value indicating the result of a string comparison.

Syntax

StrComp(string1, string2[, compare])

The StrComp function syntax has these named arguments:

Part	Description

string1	Any valid string expression.

string2	Any valid string expression.

compare	Specifies the type of string comparison.  The compare argument can be omitted, it can be 0 or 1, or it can be the value of the CollatingOrder property of a Field object.  Specify 0 (default) to perform a binary comparison.  Specify 1 to perform a textual comparison.  Specify the return value of the CollatingOrder property if you want to sort or compare values from a database in the same way the database itself would.  If compare is Null, an error occurs.  If compare is omitted, the Option Compare setting determines the type of comparison.

Return Values

If	StrComp returns

string1 is less than string2	-1

string1 is equal to string2	 0

string1 is greater than string2	 1

string1 or string2 is Null	Null


See Also

Option Compare Statement


String Function

See Also	Example

Returns a repeating character string of the length specified.

Syntax

String(number, character)

The String function syntax has these named arguments:

Part	Description

number	Length of the returned string.  If number contains Null, Null is returned.

character	Character code specifying the character or string expression whose first character is used to build the return string.  If character contains Null, Null is returned.

Remarks

If you specify a number for character greater than 255, String converts the number to a valid character code using the formula:

character Mod 256


See Also

Character Set

Mod Operator

Returning Strings From Functions

Space Function

String Data Type


UCase Function

See Also	Example

Returns a string that has been converted to uppercase.

Syntax

UCase(string)

The string argument is any valid string expression.  If string contains Null, Null is returned.

Remarks

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


See Also

LCase Function

Returning Strings From Functions


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.


Asc Function Example

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

MyNumber = Asc("A")	' Returns 65.

MyNumber = Asc("a")	' Returns 97.

MyNumber = Asc("Apple")	' Returns 65.


CBool Function Example

This example uses the CBool function to convert an expression to a Boolean.  If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

A = 5: B = 5	' Initialize variables.

Check = CBool(A = B)	' Check contains True.

A = 0	' Define variable.

Check = CBool(A)	' Check contains False.


CByte Function Example

This example uses the CByte function to convert an expression to a Byte.

MyDouble = 125.5678	' MyDouble is a Double.

MyByte = CByte(MyDouble)	' MyByte contains 126.


CDate Function Example

This example uses the CDate function to convert a string to a Date.  In general, hard coding dates and times as strings (as shown in this example) is not recommended.  Use date and time literals (such as #2/12/1969#, #4:45:23 PM#) instead.

MyDate = "February 12, 1969"	' Define date.

MyShortDate = CDate(MyDate)	' Convert to Date data type.

MyTime = "4:35:47 PM"	' Define time.

MyShortTime = CDate(MyTime)	' Convert to Date data type.


CVErr Function Example

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

' Call CalculateDouble with an error-producing argument.

Sub Test()

Debug.Print CalculateDouble("345.45robert")

End Sub

' Define CalculateDouble Function procedure.

Function CalculateDouble(Number)

If IsNumeric(Number) Then

CalculateDouble = Number * 2	' Return result.

Else

CalculateDouble = CVErr(2001)	' Return a user-defined error

End If	' number.

End Function


CCur Function Example

This example uses the CCur function to convert an expression to a Currency.

MyDouble = 543.214588	' MyDouble is a Double.

MyCurr = CCur(MyDouble * 2)	' Convert result of MyDouble * 2

' (1086.429176) to a

' Currency (1086.4292).


CDbl Function Example

This example uses the CDbl function to convert an expression to a Double.

MyCurr = CCur(234.456784)	' MyCurr is a Currency.

MyDouble = CDbl(MyCurr * 8.2 * 0.01)	' Convert result to a Double.


CInt Function Example

This example uses the CInt function to convert a value to an Integer.

MyDouble = 2345.5678	' MyDouble is a Double.

MyInt = CInt(MyDouble)	' MyInt contains 2346.


CLng Function Example

This example uses the CLng function to convert a value to a Long.

MyVal1 = 25427.45: MyVal2 = 25427.55	' MyVal1, MyVal2 are Doubles.

MyLong1 = CLng(MyVal1)	' MyLong1 contains 25427.

MyLong2 = CLng(MyVal2)	' MyLong2 contains 25428.


CSng Function Example

This example uses the CSng function to convert a value to a Single.

' MyDouble1, MyDouble2 are Doubles.

MyDouble1 = 75.3421115: MyDouble2 = 75.3421555

MySingle1 = CSng(MyDouble1)	' MySingle1 contains 75.34211.

MySingle2 = CSng(MyDouble2)	' MySingle2 contains 75.34216.


CStr Function Example

This example uses the CStr function to convert a numeric value to a String.

MyDouble = 437.324	' MyDouble is a Double.

MyString = CStr(MyDouble)	' MyString contains "437.324".


CVar Function Example

This example uses the CVar function to convert an expression to a Variant.

MyInt = 4534	' MyInt is an Integer.

MyVar = CVar(MyInt & "000")	' MyVar contains the string

' 4534000.


Val Function Example

This example uses the Val function to return the numbers contained in a string.

MyValue = Val("2457")	' Returns 2457.

MyValue = Val(" 2 45 7")	' Returns 2457.

MyValue = Val("24 and 57")	' Returns 24.


Call Statement Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, and a dynamic-link library (DLL) procedure.

' Call a Sub procedure.

Call PrintToDebugWindow("Hello World")

' The above statement causes control to be passed to the following

' Sub procedure.

Sub PrintToDebugWindow(AnyString)

Debug.Print AnyString	' Print to Debug window.

End Sub

' Call an intrinsic function. The return value of the function is

' discarded.

Call Shell(AppName, 1)	' AppName contains the path of the

' executable file.

' Call a Microsoft Windows DLL procedure.  The Declare statement must be

' Private in a Class Module, but not in a standard Module.

Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

Sub CallMyDll()

Call MessageBeep(0)	' Call Windows DLL procedure.

MessageBeep 0	' Call again without Call keyword.

End Sub


DoEvents Function Example

This example uses the DoEvents function to cause execution to yield to the operating system once every 1000 iterations of the loop.  DoEvents returns the number of open forms.

' Create a variable to hold number of Visual Basic forms loaded

' and visible.

Dim OpenForms

For I = 1 To 150000	' Start loop.

If I Mod 1000 = 0 Then 	' If loop has repeated 1000 times.

OpenForms = DoEvents	' Yield to operating system.

End If

Next I	' Increment loop counter.


Do...Loop Statement Example

This example shows how Do...Loop statements can be used.  The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement.  The outer loop exits immediately upon checking the value of the flag.

Check = True: Counter = 0	' Initialize variables.

Do	' Outer loop.

Do While Counter < 20	' Inner loop.

Counter = Counter + 1	' Increment Counter.

If Counter = 10 Then	' If condition is True.

Check = False	' Set value of flag to False.

Exit Do	' Exit inner loop.

End If

Loop

Loop Until Check = False	' Exit outer loop immediately.


End Statement Example

This example uses the End Statement to end code execution if the user enters an invalid password.

Private Sub Form_Load

PassWord = "Swordfish"

Pword = InputBox("Type in your password")

If Pword <> PassWord Then

MsgBox "Sorry, incorrect password"

End

End If

End Sub


Exit Statement Example

This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.

Sub ExitStatementDemo()

Do	' Set up infinite loop.

or I = 1 To 1000	' Loop 1000 times.

MyNum = Int(Rnd * 1000)	' Generate random numbers.

Select Case MyNum	' Evaluate random number.

Case 7: Exit For	' If 7, exit For...Next.

Case 29: Exit Do	' If 29, exit Do...Loop.

Case 54: Exit Sub	' If 54, exit Sub procedure.

End Select

Next I

Loop

End Sub


For Each...Next Statement Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello".  In the example, MyObject is a text-related object and is an element of the collection MyCollection.  Both are generic names used for illustration purposes only.

Found = False	' Initialize variable.

For Each MyObject In MyCollection	' Iterate through each element.

If MyObject.Text = "Hello" Then	' If Text equals "Hello".

Found = True	' Set Found to True.

Exit For	' Exit loop.

End If

Next


For...Next Statement Example

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space.  The outer loop uses a loop counter variable that is decremented each time through the loop.

For Words = 10 To 1 Step -1 	' Set up 10 repetitions.

For Chars = 0 To 9	' Set up 10 repetitions.

MyString = MyString & Chars	' Append number to string.

Next Chars	' Increment counter

MyString = MyString & " "	' Append a space.

Next Words


GoSub...Return Statement Example

This example uses GoSub to call a subroutine within a Sub procedure.  The Return statement causes the execution to resume at the statement immediately following the GoSub statement.  The Exit Sub statement is used to prevent control from accidentally flowing into the subroutine.

Sub GosubDemo()

' Solicit a number from the user.

Num = InputBox("Enter a positive number to be divided by 2.")

' Only use routine if user enters a positive number.

If Num > 0 Then GoSub MyRoutine

Debug.Print Num

Exit Sub	' Use Exit to prevent an error.

MyRoutine:

Num = Num/2	' Perform the division.

Return	' Return control to statement.

End Sub	' following the GoSub statement.


GoTo Statement Example

This example uses the GoTo statement to branch to line labels within a procedure.

Sub GotoStatementDemo()

Number = 1 	' Initialize variable.

' Evaluate Number and branch to appropriate label.

If Number = 1 Then GoTo Line1 Else GoTo Line2

Line1:

MyString = "Number equals 1"

G	oTo LastLine	' Go to LastLine.

Line2:

' The following statement never gets executed.

MyString = "Number equals 2"

LastLine:

Debug.Print MyString	' Print "Number equals 1" in

' Debug window.

End Sub


If...Then...Else Statement Example

This example shows both the block and single-line forms of the If...Then...Else statement.  It also illustrates the use of If TypeOf...Then...Else.

Number = 53	' Initialize variable.

If Number < 10 Then

Digits = 1

ElseIf Number < 100 Then

' Condition evaluates to True so the next statement is executed.

Digits = 2

Else

Digits = 3

End If

' Assign a value using the single-line form of syntax.

If Digits = 1 Then MyString = "One" Else MyString = "More than one"

Use If TypeOf construct to determine whether the Control passed into a procedure is a text box.

Sub ControlProcessor(MyControl As Control)

If TypeOf MyControl Is CommandButton Then

Debug.Print "You passed in a " & TypeName(MyControl)

ElseIf TypeOf MyControl Is CheckBox Then

Debug.Print "You passed in a " & TypeName(MyControl)

ElseIf TypeOf MyControl Is TextBox Then

Debug.Print "You passed in a " & TypeName(MyControl)

End If

End Sub


On...GoSub, On...GoTo Statements Example

This example uses the On...GoSub and On...GoTo statements to branch to subroutines and line labels, respectively.

Sub OnGosubGotoDemo()

Number = 2	' Initialize variable.

' Branch to Sub2.

On Number GoSub Sub1, Sub2	' Execution resumes here after

' On...GoSub.

On Number GoTo Line1, Line2	' Branch to Line2.

' Execution does not resume here after On...GoTo.

Exit Sub

Sub1:

MyString = "In Sub1" : Return

Sub2:

MyString = "In Sub2" : Return

Line1:

MyString = "In Line1"

Line2:

MyString = "In Line2"

End Sub


Select Case Statement Example

This example uses the Select Case statement to evaluate the value of a variable.  The second Case clause contains the value of the variable being evaluated, and therefore only the statement associated with it is executed.

Number = 8	' Initialize variable.

Select Case Number	' Evaluate Number.

Case 1 To 5	' Number between 1 and 5.

Debug.Print "Between 1 and 5"

' The following is the only Case clause that evaluates to True.

Case 6, 7, 8	' Number between 6 and 8.

Debug.Print "Between 6 and 8"

Case Is > 8 And Number < 11	' Number is 9 or 10.

Debug.Print "Greater than 8"

Case Else	' Other values.

Debug.Print "Not between 1 and 10"

End Select


Shell Function Example

This example uses the Shell function to run an application specified by the user.

' In Microsoft Windows:

' Specifying 1 as the second argument opens the application in

' normal size and gives it the focus.

RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)	' Run Calculator.


Stop Statement Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

For I = 1 To 10	' Start For...Next loop.

Debug.Print I	' Print I to Debug window.

Stop	' Stop during each iteration.

Next I


While...Wend Statement Example

This example uses the While...Wend statement to increment a counter variable.  The statements in the loop are executed as long as the condition evaluates to True.

Counter = 0	' Initialize variable.

While Counter < 20	' Test value of Counter.

Counter = Counter + 1	' Increment Counter.

Wend	' End While loop when Counter > 19.

Debug.Print Counter	' Prints 20 in Debug window.


With Statement Example

This example uses the With statement to execute a series of statements on a single object.  The object MyObject and its properties are generic names used for illustration purposes only.

With MyObject

.Height = 100	' Same as MyObject.Height = 100.

.Caption = "Hello World"	' Same as MyObject.Caption = "Hello World".

With .Font

.Color = Red	' Same as MyObject.Font.Color = Red.

.Bold = True	' Same as MyObject.Font.Bold = True.

End With

End With


Date Function Example

This example uses the Date function to return the current system date.

MyDate = Date	' MyDate contains the current system date.


Date Statement Example

This example uses the Date statement to set the computer system date.  In the development environment, the date literal is displayed in short date format using the locale settings of your code.

MyDate = #February 12, 1985#	' Assign a date.

Date = MyDate	' Change system date.


DateSerial Function Example

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

' MyDate contains the date for February 12, 1969.

MyDate = DateSerial(1969, 2, 12)	' Return a date.


DateValue Function Example

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

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


Day Function Example

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

MyDate = #February 12, 1969#	' Assign a date.

MyDay = Day(MyDate)	' MyDay contains 12.


Hour Function Example

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

MyTime = #4:35:17 PM#	' Assign a time.

MyHour = Hour(MyTime)	' MyHour contains 16.


Minute Function Example

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

MyTime = #4:35:17 PM#	' Assign a time.

MyMinute = Minute(MyTime)	' MyMinute contains 35.


Month Function Example

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

MyDate = #February 12, 1969#	' Assign a date.

MyMonth = Month(MyDate)	' MyMonth contains 2.


Now Function Example

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

Today = Now	' Assign current system date and time.


Second Function Example

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

MyTime = #4:35:17 PM#	' Assign a time.

MySecond = Second(MyTime)	' MySecond contains 17.


Time Function Example

This example uses the Time function to return the current system time.

MyTime = Time	' Return current system time.


Time Statement Example

This example uses the Time statement to set the computer system time to a user-defined time.

MyTime = #4:35:17 PM#	' Assign a time.

Time = MyTime	' Set system time to MyTime.


Timer Function Example

This example uses the Timer function to pause the application.  The example also uses DoEvents to yield to other processes during the pause.

If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then

PauseTime = 5	' Set duration.

Start = Timer	' Set start time.

Do While Timer < Start + PauseTime

DoEvents	' Yield to other processes.

Loop

Finish = Timer	' Set end time.

TotalTime = Finish - Start	' Calculate total time.

MsgBox "Paused for " & TotalTime & " seconds"

Else

End

End If


TimeSerial Function Example

This example uses the TimeSerial function to return a time for the specified hour, minute, and second.

MyTime = TimeSerial(16, 35, 17)	' MyTime contains serial

' representation of 4:35:17 PM.


TimeValue Function Example

This example uses the TimeValue function to convert a string to a time.  You can also use date literals to directly assign a time to a Variant or Date variable (for example, MyTime = #4:35:17 PM#).

MyTime = TimeValue("4:35:17 PM")	' Return a time.


Weekday Function Example

This example uses the Weekday function to obtain the day of the week from a specified date.

MyDate = #February 12, 1969#	' Assign a date.

MyWeekDay = Weekday(MyDate)	' MyWeekDay contains 4 because

' MyDate represents a Wednesday.


Year Function Example

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

MyDate = #February 12, 1969#	' Assign a date.

MyYear = Year(MyDate)	' MyYear contains 1969.


Array Function Example

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

MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

' Return values assume lower bound set to 1 (using Option Base

' statement).

MyDay = MyWeek(2)	' MyDay contains "Tue".

MyDay = MyWeek(4)	' MyDay contains "Thu".


Const Statement Example

This example uses the Const statement to declare constants for use in place of literal values.  Public constants occur in a the General section of a standard module, rather than a Class Module.  Private constants can go in the General section of any type of module.

' Constants are Private by default.

Const MyVar = 459

' Declare Public constant.

Public Const MyString = "HELP"

' Declare Private Integer constant.

Private Const MyInt As Integer = 5

' Declare multiple constants on same line.

Const MyStr = "Hello", MyDouble As Double = 3.4567


Declare Statement Example

This example shows how the Declare statement is used at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL).  You can place the Declare statements in Class Modules if the Declare statements are Private.

Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

' Assume SomeBeep is an alias for the procedure name.

Declare Sub MessageBeep Lib "User" Alias "SomeBeep"(ByVal N As Integer)

' Use an ordinal in the Alias clause to call GetWinFlags.

Declare Function GetWinFlags Lib "Kernel" Alias "#132"() As Long

' In 32-bit Microsoft Windows systems, specify the library USER32.DLL,

' rather than USER.DLL.  You can use conditional compilation to write

' code that can run on either Win32 or Win16.

#If Win32 Then

Declare Sub MessageBeep Lib "User32" (ByVal N As Long)

#Else

Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

#End If


Deftype Statements Example

This example shows various uses of the Deftype statements to set default data types of variables and function procedures whose names start with specified characters.  The default data type can be overridden only by explicit assignment using the Dim statement.  Deftype statements can only be used at the module level (that is, not within procedures).

' Variable names beginning with A through K default to Integer.

DefInt A-K

' Variable names beginning with L through Z default to String.

DefStr L-Z

CalcVar = 4	' Initialize Integer.

StringVar = "Hello there"	' Initialize String.

AnyVar = "Hello" 	' Causes "Type mismatch" error.

Dim Calc As Double	' Explicitly set the type to Double.

Calc = 2.3455	' Assign a Double.

' Deftype statements also apply to function procedures.

CalcNum = ATestFunction(4)	' Call user-defined function.

' ATestFunction function procedure definition.

Function ATestFunction(INumber)

ATestFunction = INumber * 2	' Return value is an integer.

End Function


Dim Statement Example

This example shows various uses of the Dim statement to declare variables.  It also shows the Dim statement being used to declare arrays.  The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.

' AnyValue and MyValue are declared as Variant by default with values

' set to Empty.

Dim AnyValue, MyValue

' Explicitly declare a variable of type Integer.

Dim Number As Integer

' Multiple declarations on a single line. AnotherVar is of type Variant

' because its type is omitted.

Dim AnotherVar, Choice As Boolean, BirthDate As Date

' DayArray is an array of Variants with 51 elements indexed, from

' 0 thru 50, assuming Option Base is set to 0 (default) for

' the current module.

Dim DayArray(50)

' Matrix is a two-dimensional array of integers.

Dim Matrix(3, 4) As Integer

' MyMatrix is a three-dimensional array of doubles with explicit

' bounds.

Dim MyMatrix(1 To 5,  4 To 9,  3 To 5) As Double

' BirthDay is an array of dates with indexes from 1 to 10.

Dim BirthDay(1 To 10) As Date

' MyArray is a dynamic array of variants.

Dim MyArray()


Erase Statement Example

This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.

' Declare array variables.

Dim NumArray(10) As Integer	' Integer array.

Dim StrVarArray(10) As String	' Variable-string array.

Dim StrFixArray(10) As String * 10	' Fixed-string array.

Dim VarArray(10) As Variant	' Variant array.

Dim DynamicArray() As Integer	' Dynamic array.

ReDim DynamicArray(10)	' Allocate storage space.

Erase NumArray	' Each element set to 0.

Erase StrVarArray	' Each element set to zero-length

' string ("").

Erase StrFixArray	' Each element set to 0.

Erase VarArray	' Each element set to Empty.

Erase DynamicArray	' Free memory used by array.


Function Statement Example

This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure.  A named argument is used in last example.

' The following user-defined function returns the square root of the

' argument passed to it.

Function CalculateSquareRoot(NumberArg As Double) As Double

If NumberArg < 0 Then	' Evaluate argument.

Exit Function	' Exit to calling procedure.

Else

CalculateSquareRoot = Sqr(NumberArg)	' Return square root.

End If

End Function

Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, FirstArg is passed by value.

Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())

' If the function is invoked as follows:

ReturnValue = CalcSum(4, 3 ,2 ,1)

' Local variables are assigned the following values: FirstArg = 4,

' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default

' lowerbound for arrays = 1.

' If a function's arguments are defined as follows:

Function MyFunc(MyStr As String, Optional MyArg1, Optional MyArg2)

' The function can be invoked as follows:

RetVal = MyFunc("Hello", 2, "World")	' All 3 arguments supplied.

RetVal = MyFunc("Test", , 5)	' Second argument omitted.

RetVal = MyFunc(MyArg1 := 7)	' Second argument only,

' using named-argument.


LBound Function Example

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

Dim MyArray(1 To 10, 5 To 15, 10 To 20) 	' Declare array variables.

Dim AnyArray(10)

Lower = LBound(MyArray, 1) 	' Returns 1.

Lower = LBound(MyArray, 3)	' Returns 10.

Lower = LBound(AnyArray)	' Returns 0 or 1, depending on

' setting of Option Base.


Let Statement Example

This example assigns the values of expressions to variables using both the explicit and implicit Let statement.

' The following variable assignments use the Let statement.

Let MyStr = "Hello World"

Let MyInt = 5

The following are the same assignments without the Let statement.

MyStr = "Hello World"

MyInt = 5


Option Base Statement Example

This example uses the Option Base statement to override the default base array subscript value of 0.  The LBound function returns the smallest available subscript for the indicated dimension of an array.  The Option Base statement is used at the module level only.

Option Base 1	' Set default array subscripts to 1.

Dim MyArray(20), TwoDArray(3, 4)	' Declare array variables.

Dim ZeroArray(0 To 5)	' Override default base subscript.

' Use LBound function to test lower bounds of arrays.

Lower = LBound(MyArray)	' Returns 1.

Lower = LBound(TwoDArray, 2)	' Returns 1.

Lower = LBound(ZeroArray)	' Returns 0.


Option Compare Statement Example

This example uses the Option Compare statement to set the default string comparison method.  The Option Compare statement is used at the module level only.

' Set the string comparison method to Binary.

Option Compare Binary 	' That is, "AAA" is less than "aaa"

' Set the string comparison method to Text.

Option Compare Text	' That is, "AAA" is equal to "aaa".


Option Explicit Statement Example

This example uses the Option Explicit statement to force you to explicitly declare all variables.  Attempting to use an undeclared variable causes an error at compile time.  The Option Explicit statement is used at the module level only.

Option Explicit	' Force explicit variable declaration.

Dim MyVar	' Declare variable.

MyInt = 10	' Undeclared variable generates error.

MyVar = 10	' Declared variable does not generate error.


Private Statement Example

This example shows the Private statement being used at the module level to declare variables as private; that is, they are available only to the module in which they are declared.

Private Number As Integer	' Private Integer variable.

Private NameArray(1 To 5) As String	' Private array variable.

' Multiple declarations, two Variants and one Integer, all Private.

Private MyVar, YourVar, ThisVar As Integer


Property Get Statement Example

This example uses the Property Get Statement to define a property procedure that gets the value of a property.  The property identifies, as a string, the current color of a pen in a drawing package.

Dim CurrentColor As Integer

Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Returns the current color of the pen as a string.

Property Get PenColor() As String

Select Case CurrentColor

Case RED

PenColor = "Red"

Case GREEN

PenColor = "Green"

Case BLUE

PenColor = "Blue"

End Select

End Property

' The following code gets the color of the pen

' calling the Property Get procedure.

ColorName = PenColor()


Property Let Statement Example

This example uses the Property Let statement to define a procedure that assigns a value to a property.  The property identifies the pen color for a drawing package.

Dim CurrentColor As Integer

Const BLACK = 0, RED = 1, GREEN = 2, BLUE = 3

' Set the pen color property for a Drawing package.

' The module-level variable CurrentColor is set to

' a numeric value that identifies the color used for drawing.

Property Let PenColor(ColorName As String)

Select Case ColorName	' Check color name string.

Case "Red"

CurrentColor = RED	' Assign value for Red.

Case "Green"

CurrentColor = GREEN	' Assign value for Green.

Case "Blue"

CurrentColor = BLUE	' Assign value for Blue.

Case Else

CurrentColor = BLACK	' Assign default value.

End Select

End Property

' The following code sets the PenColor property for a drawing package

' by calling the Property Let procedure.

PenColor() = "Red"


Property Set Statement Example

This example uses the Property Set statement to define a property procedure that sets a reference to an object.

' The Pen property may be set to different Pen implementations.

Property Set Pen(P As Object)

Set CurrentPen = P	' Assign Pen to object.

End Property


Public Statement Example

This example uses the Public statement at the module level (General section) of a standard module to explicitly declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.

Public Number As Integer	' Public Integer variable.

Public NameArray(1 To 5) As String	' Public array variable.

' Multiple declarations, two Variants and one Integer, all Public.

Public MyVar, YourVar, ThisVar As Integer


ReDim Statement Example

This example uses the ReDim statement to allocate and reallocate storage space for dynamic-array variables.  It assumes the Option Base is 1.

Dim MyArray() As Integer	' Declare dynamic array.

ReDim MyArray(5)	' Allocate 5 elements.

For I = 1 To 5	' Loop 5 times.

MyArray(I) = I	' Initialize array.

Next I

The next statement resizes the array and erases the elements.

ReDim MyArray(10)	' Resize to 10 elements.

For I = 1 To 10	' Loop 10 times.

MyArray(I) = I	' Initialize array.

Next I

The following statement resizes the array but does not erase elements.

ReDim Preserve MyArray(15)	' Resize to 15 elements.


Rem Statement Example

This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.

Rem This is the first form of the syntax.

The following shows the second form of the syntax.

MyStr1 = "Hello": Rem Comment after a statement separated by a colon.

MyStr2 = "Goodbye" 	' This is also a comment; no colon is needed.


Set Statement Example

This example uses the Set statement to assign object references to variables.  YourObject is assumed to be a valid object with a Text property.

Set MyObject = YourObject	' Assign object reference.

' MyObject and YourObject refer to the same object.

YourObject.Text = "Hello World"	' Initialize property.

MyStr = MyObject.Text	' Returns "Hello World".

' Discontinue association. MyObject no longer refers to YourObject.

Set MyObject = Nothing	' Release the object.


Static Statement Example

This example uses the Static statement to retain the value of a variable for as long as module code is running.

' Function definition.

Function KeepTotal(Number)

' Only the variable Accumulate preserves its value between calls.

Static Accumulate

Accumulate = Accumulate + Number

KeepTotal = Accumulate

End Function

' Static function definition.

Static Function MyFunction(Arg1, Arg2, Arg3)

' All local variables preserve value between function calls.

Accumulate = Arg1 + Arg2 + Arg3

Half = Accumulate / 2

MyFunction = Half

End Function


Sub Statement Example

This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.

' Sub procedure definition.

Sub SubComputeArea(Length, TheWidth)	' Sub procedure with two

' arguments.

Dim Area As Double	' Declare local variable.

If Length = 0 Or TheWidth = 0 Then	' If either argument = 0.

Exit Sub	' Exit Sub immediately.

End If

Area = Length * TheWidth	' Calculate area of rectangle.

Debug.Print Area	' Print Area to Debug window.

End Sub


Type Statement Example

This example uses the Type statement to define a user-defined data type.  The Type statement is used at the module level only.  If it appears in a Class Module, a Type statement must be preceded by the keyword Private.

Type EmployeeRecord	' Create user-defined type.

ID As Integer	' Define elements of data type.

Name As String * 20

Address As String * 30

Phone As Long

HireDate As Date

End Type

Dim MyRecord As EmployeeRecord	' Declare variable.

' Assignment to EmployeeRecord variable must occur in a procedure.

MyRecord.ID = 12003	' Assign a value to an element.


UBound Function Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Dim MyArray(1 To 10, 5 To 15, 10 To 20)	' Declare array variables.

Dim AnyArray(10)

Upper = UBound(MyArray, 1)	' Returns 10.

Upper = UBound(MyArray, 3)	' Returns 20.

Upper = UBound(AnyArray)	' Returns 10.


Close Statement Example

This example uses the Close statement to close all three files opened for Output.

For I = 1 To 3	' Loop 3 times.

FileName = "TEST" & I	' Create filename.

Open FileName For Output As #I	' Open file.

Print #I, "This is a test."	' Write string to file.

Next I

Close	' Close all 3 open files.


EOF Function Example

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

Open "MYFILE" For Input As #1	' Open file for input.

Do While Not EOF(1)	' Check for end of file.

Line Input #1, InputData	' Read line of data.

Debug.Print InputData	' Print to Debug window.

Loop

Close #1	' Close file.


FileAttr Function Example

This example uses the FileAttr function to return the file mode and file handle of an open file.

FileNum = 1	' Assign file number.

Open "TESTFILE" For Append As FileNum	' Open file.

Mode = FileAttr(FileNum, 1)	' Returns 8 (Append file mode).

Handle = FileAttr(FileNum, 2)	' Returns file handle.

Close FileNum	' Close file.


FreeFile Function Example

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

For MyIndex = 1 To 5	' Loop 5 times.

FileNumber = FreeFile	' Get unused file

' number.

Open "TEST" & MyIndex For Output As #FileNumber	' Create filename.

Write #FileNumber, "This is a sample."	' Output text.

Close #FileNumber	' Close file.

Next MyIndex


Get Statement Example

This example uses the Get statement to read data from a file into a variable.  This example assumes that TESTFILE is a file containing five records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open sample file for random access.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

' Read the sample file using the Get statement.

Position = 3	' Define record number.

Get #1, Position, MyRecord	' Read third record.

Close #1	' Close file.


Input # Statement Example

This example uses the Input # statement to read data from a file into two variables.  This example assumes that TESTFILE is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, ("Hello", 234).

Open "TESTFILE" For Input As #1	' Open file for input.

Do While Not EOF(1)	' Loop until end of file.

Input #1, MyString, MyNumber	' Read data into two variables.

Debug.Print MyString, MyNumber	' Print data to Debug window.

Loop

Close #1	' Close file.


Input Function Example

This example uses the Input function to read one character at a time from a file and print it to the Debug window.  This example assumes that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1	' Open file.

Do While Not EOF(1)	' Loop until end of file.

MyChar = Input(1, #1)	' Get one character.

Debug.Print MyChar	' Print to Debug window.

Loop

Close #1	' Close file.


Line Input # Statement Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable.  This example assumes that TESTFILE is a text file with a few lines of sample data.

Open "TESTFILE" For Input As #1	' Open file.

Do While Not EOF(1)	' Loop until end of file.

Line Input #1, TextLine	' Read line into variable.

Debug.Print TextLine	' Print to Debug window.

Loop

Close #1	' Close file.


Loc Function Example

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

Open "TESTFILE" For Binary As #1	' Open file just created.

Do While MyLocation < LOF(1)	' Loop until end of file.

MyLine = MyLine & Input(1, #1)	' Read character into variable.

MyLocation = Loc(1)	' Get current position within file.

' Print to Debug window.

Debug.Print MyLine; Tab; MyLocation

Loop

Close #1	' Close file.


Lock, Unlock Statements Example

This example illustrates the use of the Lock and Unlock statements.  While a record is being modified, access by other processes to the record is denied.  This example assumes that TESTFILE is a file containing five records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open sample file for random access.

Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord)

RecordNumber = 4	' Define record number.

Lock #1, RecordNumber	' Lock record.

Get #1, RecordNumber, MyRecord	' Read record.

MyRecord.ID = 234	' Modify record.

MyRecord.Name = "John Smith"

Put #1, RecordNumber, MyRecord	' Write modified record.

Unlock #1, RecordNumber	' Unlock current record.

Close #1	' Close file.


LOF Function Example

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

Open "TESTFILE" For Input As #1	' Open file.

FileLength = LOF(1)	' Get length of file.

Close #1	' Close file.


Open Statement Example

This example illustrates various uses of the Open statement to enable input and output to a file.

The following code opens the file TESTFILE in sequential-input mode.

Open "TESTFILE" For Input As #1

' Close before reopening in another mode.

Close #1

This example opens the file in Binary mode for writing operations only.

Open "TESTFILE" For Binary Access Write As #1

' Close before reopening in another mode.

Close #1

The following example opens the file in Random mode.  The file contains records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

' Close before reopening in another mode.

Close #1

This code example opens the file for sequential output; any process can read or write to file.

Open "TESTFILE" For Output Shared As #1

' Close before reopening in another mode.

Close #1

This code example opens the file in Binary mode for reading; other processes cannot read file.

Open "TESTFILE" For Binary Access Read Lock Read As #1


Print # Statement Example

This example uses the Print # statement to write data to a file.

Open "TESTFILE" For Output As #1	' Open file for output.

Print #1, "This is a test"	' Print text to file.

Print #1,	' Print blank line to file.

Print #1, "Zone 1"; Tab ; "Zone 2"	' Print in two print zones.

Print #1, "Hello" ; " " ; "World"	' Separate strings with space.

Print #1, Spc(5) ; "5 leading spaces "	' Print five leading spaces.

Print #1, Tab(10) ; "Hello"	' Print word at column 10.

' Assign Boolean, Date, Null and Error values.

MyBool = False : MyDate = #February 12, 1969# : MyNull = Null

MyError = CVErr(32767)

' True, False, Null, and Error are translated using locale settings of

' your system. Date literals are written using standard short date

' format.

Print #1, MyBool ; " is a Boolean value"

Print #1, MyDate ; " is a date"

Print #1, MyNull ; " is a null value"

Print #1, MyError ; " is an error value"

Close #1	' Close file.


Put Statement Example

This example uses the Put statement to write data to a file.  Five records of the user-defined type Record are written to the file.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

Dim MyRecord As Record	' Declare variable.

' Open file for random access.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

For RecordNumber = 1 To 5	' Loop 5 times.

MyRecord.ID = RecordNumber	' Define ID.

MyRecord.Name = "My Name" & RecordNumber	' Create a string.

Put #1, RecordNumber, MyRecord	' Write record to file.

Next RecordNumber

Close #1	' Close file.


Reset Statement Example

This example uses the Reset statement to close all open files and write the contents of all file buffers to disk.  Note the use of the Variant variable FileNumber as both a string and a number.

For FileNumber = 1 To 5	' Loop 5 times.

' Open file for output. FileNumber is concatenated into the string

' TEST for the filename, but is a number following a #.

Open "TEST" & FileNumber For Output As #FileNumber

Write #FileNumber, "Hello World"	' Write data to file.

Next FileNumber

Reset	' Close files and write contents

' to disk.


Seek Function Example

This example uses the Seek function to return the current file position.  The example assumes TESTFILE is a file containing records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

For files opened in random-file mode, Seek returns number of next record.

Dim MyRecord As Record	' Declare variable.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

Do While Not EOF(1)	' Loop until end of file.

Get #1, , MyRecord	' Read next record.

Debug.Print Seek(1)	' Print record number to Debug

' window.

Loop

Close #1	' Close file.

For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place.  Assume TESTFILE is a file containing a few lines of text.

Open "TESTFILE" For Input As #1	' Open file for reading.

Do While Not EOF(1)	' Loop until end of file.

MyChar = Input(1, #1)	' Read next character of data.

Debug.Print Seek(1)	' Print byte position to Debug

' window.

Loop

Close #1	' Close file.


Seek Statement Example

This example uses the Seek statement to set the position for the next read or write within a file.  This example assumes TESTFILE is a file containing records of the user-defined type Record.

Type Record	' Define user-defined type.

ID As Integer

Name As String * 20

End Type

For files opened in random-file mode, Seek sets the next record.

Dim MyRecord As Record	' Declare variable.

' Open file in random-file mode.

Open "TESTFILE" For Random As #1 Len = Len(MyRecord)

MaxSize = LOF(1) \ Len(MyRecord)	' Get number of records in file.

' The loop reads all records starting from the last.

For RecordNumber = MaxSize To 1 Step - 1

Seek #1, RecordNumber	' Set position.

Get #1, , MyRecord	' Read record.

Next RecordNumber

Close #1	' Close file.

For files opened in modes other than Random mode, Seek sets the byte position at which the next operation will take place.  Assume TESTFILE is a file containing a few lines of text.

Open "TESTFILE" For Input As #1	' Open file for input.

MaxSize = LOF(1)	' Get size of file in bytes.

' The loop reads all characters starting from the last.

For NextChar = MaxSize To 1 Step -1

Seek #1, NextChar	' Set position.

MyChar = Input(1, #1)	' Read character.

Next NextChar

Close #1	' Close file.


Spc Function Example

This example uses the Spc function to position output in a file and in the Debug window.

' The Spc function can be used with the Print # statement.

Open "TESTFILE" For Output As #1	' Open file for output.

Print #1, "10 spaces between here"; Spc(10); "and here."

Close #1	' Close file.

The following statement causes the text to be printed in the Debug window (using the Print method), preceded by 30 spaces.

Debug.Print Spc(30); "Thirty spaces later..."


Tab Function Example

This example uses the Tab function to position output in a file and in the Debug window.

' The Tab function can be used with the Print # statement.

Open "TESTFILE" For Output As #1	' Open file for output.

' The second word prints at column 20.

Print #1, "Hello"; Tab(20); "World."

' If the argument is omitted, cursor is moved to the next print zone.

Print #1, "Hello"; Tab; "World"

Close #1	' Close file.

The Tab function can also be used with the Print method.  The following statement prints text starting at column 10.

Debug.Print Tab(10); "10 columns from start."


Width # Statement Example

This example uses the Width # statement to set the output-line width for a file.

Open "TESTFILE" For Output As #1	' Open file for output.

Width #1, 5	' Set output-line width to 5.

For I = 0 To 9	' Loop 10 times.

Print #1, Chr(48 + I);	' Prints five characters per line.

Next I

Close #1	' Close file.


Write # Statement Example

This example uses the Write # statement to write raw data to a sequential file.

Open "TESTFILE" For Output As #1	' Open file for output.

Write #1, "Hello World", 234	' Write comma delimited data .

Write #1,	' Write blank line.

' Assign Boolean, Date, Null, and Error values.

MyBool = False : MyDate = #February 12, 1969# : MyNull = Null

MyError = CVErr(32767)

' Boolean data is written as #TRUE# or #FALSE#. Date literals are

' written in universal date format, for example, #1994-07-13#

 'represents July 13, 1994. Null data is written as #NULL#.

' Error data is written as #ERROR errorcode#.

Write #1, MyBool ; " is a Boolean value"

Write #1, MyDate ; " is a date"

Write #1, MyNull ; " is a null value"

Write #1, MyError ; " is an error value"

Close #1	' Close file.


ChDir Statement Example

This example uses the ChDir statement to change the current directory.

' Change current directory to "MYDIR".

ChDir "MYDIR"

' Assume "C:" is the current drive.  The following statement changes

' the default directory on drive "D:". "C:" remains the current drive.

ChDir "D:\WINDOWS\SYSTEM"


ChDrive Statement Example

This example uses the ChDrive statement to change the current drive.

ChDrive "D"	' Make "D" the current drive.


CurDir Function Example

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

' Assume current path on C drive is "C:\WINDOWS\SYSTEM".

' Assume current path on D drive is "D:\EXCEL".

' Assume C is the current drive.

MyPath = CurDir	' Returns "C:\WINDOWS\SYSTEM".

MyPath = CurDir("C")	' Returns "C:\WINDOWS\SYSTEM".

MyPath = CurDir("D")	' Returns "D:\EXCEL".


Dir Function Example

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

' Returns "WIN.INI" if it exists.

MyFile = Dir("C:\WINDOWS\WIN.INI")

' Returns filename with specified extension. If more than one *.ini

' file exists, the first file found is returned.

MyFile = Dir("C:\WINDOWS\*.INI")

' Call Dir again without arguments to return the next *.INI file in the

' same directory.

MyFile = Dir

' Return first *.TXT file with a set hidden attribute.

MyFile = Dir("*.TXT", vbHidden)

' Display the names in C:\ that represent directories.

MyPath = "c:\"	' Set the path.

MyName = Dir(MyPath, vbDirectory)	' Retrieve the first entry.

Do While MyName <> ""	' Start the loop.

' Ignore the current directory and the encompassing directory.

If MyName <> "." And MyName <> ".." Then

' Use bitwise comparison to make sure MyName is a directory.

If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then

Debug.Print MyName	' Display entry only if it

End If	' it represents a directory.

End If

MyName = Dir	' Get next entry.

Loop


FileCopy Statement Example

This example uses the FileCopy statement to copy one file to another.  For purposes of this example, assume that SRCFILE is a file containing some data.

SourceFile = "SRCFILE"	' Define source filename.

DestinationFile = "DESTFILE"	' Define target filename.

FileCopy SourceFile, DestinationFile	' Copy source to target.


FileDateTime Function Example

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

' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM.

' Assume English/United States locale settings.

MyStamp = FileDateTime("TESTFILE")	' Returns "2/12/93 4:35:47 PM".


FileLen Function Example

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

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


GetAttr Function Example

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

' Assume file TESTFILE has hidden attribute set.

MyAttr = GetAttr("TESTFILE")	' Returns 2.

' Returns nonzero if hidden attribute is set on TESTFILE.

Debug.Print MyAttr And vbHidden

' Assume file TESTFILE has hidden and read-only attributes set.

MyAttr = GetAttr("TESTFILE")	' Returns 3.

' Returns nonzero if hidden attribute is set on TESTFILE.

Debug.Print MyAttr And (vbHidden + vbReadOnly)

' Assume MYDIR is a directory.

MyAttr = GetAttr("MYDIR")	' Returns 16.


Kill Statement Example

This example uses the Kill statement to delete a file from a disk.

' Assume TESTFILE is a file containing some data.

Kill "TestFile"	' Delete file.

' Delete all *.TXT files in current directory.

Kill "*.TXT"


MkDir Statement Example

This example uses the MkDir statement to create a directory.  If the drive is not specified, the new directory is created on the current drive.

MkDir "MYDIR"	' Make new directory.


Name Statement Example

This example uses the Name statement to rename a file.  For purposes of this example, assume that the directories that are specified already exist.

OldName = "OLDFILE": NewName = "NEWFILE"	' Define filenames.

Name OldName As NewName	' Rename file.

OldName = "C:\MYDIR\OLDFILE": NewName = "C:\YOURDIR\NEWFILE"

Name OldName As NewName	' Move and rename file.


RmDir Statement Example

This example uses the RmDir statement to remove an existing directory.

' Assume that MYDIR is an empty directory.

RmDir "MYDIR"	' Remove MYDIR.


SetAttr Statement Example

This example uses the SetAttr statement to set attributes for a file.

SetAttr "TESTFILE", vbHidden	' Set hidden attribute.

SetAttr "TESTFILE", vbHidden + vbReadOnly	' Set hidden and read-only

' attributes.


IsArray Function Example

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

Dim MyArray(1 To 5) As Integer	' Declare array variable.

YourArray = Array(1, 2, 3)	' Use Array function.

MyCheck = IsArray(MyArray)	' Returns True.

MyCheck = IsArray(YourArray)	' Returns True.


IsDate Function Example

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

MyDate = "February 12, 1969": YourDate = #2/12/69#: NoDate = "Hello"

MyCheck = IsDate(MyDate)	' Returns True.

MyCheck = IsDate(YourDate)	' Returns True.

MyCheck = IsDate(NoDate)	' Returns False.


IsEmpty Function Example

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

MyCheck = IsEmpty(MyVar)	' Returns True.

MyVar = Null	' Assign Null.

MyCheck = IsEmpty(MyVar)	' Returns False.

MyVar = Empty	' Assign Empty.

MyCheck = IsEmpty(MyVar)	' Returns True.


IsError Function Example

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

ReturnVal = UserFunction()

MyCheck = IsError(ReturnVal)	' Returns True.


IsMissing Function Example

This example uses the IsMissing function to check if an optional argument has been passed to a user-defined procedure.

' The following statements call the user-defined function procedure.

ReturnValue = ReturnTwice()	' Returns Null.

ReturnValue = ReturnTwice(2)	' Returns 4.

' Function procedure definition.

Function ReturnTwice(Optional A)

If IsMissing(A) Then

' If argument is missing, return a Null.

ReturnTwice = Null

Else

' If argument is present, return twice the value.

ReturnTwice = A * 2

End If

End Function


IsNull Function Example

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

MyCheck = IsNull(MyVar)	' Returns False.

MyVar = ""

MyCheck = IsNull(MyVar)	' Returns False.

MyVar = Null

MyCheck = IsNull(MyVar)	' Returns True.


IsNumeric Function Example

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

MyVar = "53"	' Assign value.

MyCheck = IsNumeric(MyVar)	' Returns True.

MyVar = "459.95"	' Assign value.

MyCheck = IsNumeric(MyVar)	' Returns True.

MyVar = "45 Help"	' Assign value.

MyCheck = IsNumeric(MyVar)	' Returns False.


IsObject Function Example

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

Dim MyInt As Integer	' Declare variables.

Dim MyObject As Object

Set YourObject = MyObject	' Assign an object reference.

MyCheck = IsObject(YourObject)	' Returns True.

MyCheck = IsObject(MyInt)	' Returns False.


TypeName Function Example

This example uses the TypeName function to return information about a variable.

' Declare variables.

Dim StrVar As String, IntVar As Integer, CurVar As Currency

Dim ArrayVar (1 To 5) As Integer

NullVar = Null	' Assign Null value.

MyType = TypeName(StrVar)	' Returns "String".

MyType = TypeName(IntVar)	' Returns "Integer".

MyType = TypeName(CurVar)	' Returns "Currency".

MyType = TypeName(NullVar)	' Returns "Null".

MyType = TypeName(ArrayVar)	' Returns "Integer()".


VarType Function Example

This example uses the VarType function to determine the subtype of a variable.

' Initialize variables.

IntVar = 459: StrVar = "Hello World": DateVar = #2/12/69#

MyCheck = VarType(IntVar)	' Returns 2.

MyCheck = VarType(DateVar)	' Returns 7.

MyCheck = VarType(StrVar)	' Returns 8.


Abs Function Example

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

MyNumber = Abs(50.3)	' Returns 50.3.

MyNumber = Abs(-50.3)	' Returns 50.3.


Atn Function Example

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

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


Cos Function Example

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

MyAngle = 1.3	' Define angle in radians.

MySecant = 1 / Cos(MyAngle)	' Calculate secant.


Exp Function Example

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

' Define angle in radians.

MyAngle = 1.3

' Calculate hyperbolic sine.

MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2


Int Function, Fix Function Example

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

MyNumber = Int(99.8)	' Returns 99.

MyNumber = Fix(99.2)	' Returns 99.

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

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

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

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


Log Function Example

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

' Define angle in radians.

MyAngle = 1.3

' Calculate inverse hyperbolic sine.

MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1))


Randomize Statement Example

This example uses the Randomize statement to initialize the random-number generator.  Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

Randomize	' Initialize random-number generator.

MyValue = Int((6 * Rnd) + 1)	' Generate random value between 1 and 6.


Rnd Function Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

MyValue = Int((6 * Rnd) + 1)	' Generate random value between 1 and 6.


Sgn Function Example

This example uses the Sgn function to determine the sign of a number.

MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0

MySign = Sgn(MyVar1)	' Returns 1.

MySign = Sgn(MyVar2)	' Returns -1.

MySign = Sgn(MyVar3)	' Returns 0.


Sin Function Example

This example uses the Sin function to return the sine of an angle.

MyAngle = 1.3	' Define angle in radians.

MyCosecant = 1 / Sin(MyAngle)	' Calculate cosecant.


Sqr Function Example

This example uses the Sqr function to calculate the square root of a number.

MySqr = Sqr(4)	' Returns 2.

MySqr = Sqr(23)	' Returns 4.79583152331272.

MySqr = Sqr(0)	' Returns 0.

MySqr = Sqr(-4)	' Generates a run-time error.


Tan Function Example

This example uses the Tan function to return the tangent of an angle.

MyAngle = 1.3	' Define angle in radians.

MyCotangent = 1 / Tan(MyAngle)	' Calculate cotangent.


AppActivate Statement Example

This example illustrates various uses of the AppActivate statement to activate an application window.  The Shell statements assume the applications are in the paths specified.  .

AppActivate "Microsoft Word"	' Activate Microsoft

' Word.

' AppActivate can also use the return value of the Shell function.

MyAppID = Shell("C:\WORD\WINWORD.EXE", 1)	' Run Microsoft Word.

AppActivate MyAppID	' Activate Microsoft

' Word.


Beep Statement Example

This example uses the Beep statement to sound three consecutive tones through the computer's speaker.

For I = 1 To 3	' Loop 3 times.

Beep	' Sound a tone.

Next I


InputBox Function Example

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

Message = "Enter a value between 1 and 3"	' Set prompt.

Title = "InputBox Demo"	' Set title.

Default = "1"	' Set default.

' Display message, title, and default value.

MyValue = InputBox(Message, Title, Default)

' Use Helpfile and context. The Help button is added automatically.

MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog box at position 100, 100.

MyValue = InputBox(Message, Title, Default, 100, 100)


MsgBox Function Example

This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons.  The No button is specified as the default response.  The value returned by the MsgBox function depends on the button chosen by the user.  This example assumes that DEMO.HLP is a Help file that contains a topic with a Help context number equal to 1000.

Msg = "Do you want to continue ?"	' Define message.

Style = vbYesNo + vbCritical + vbDefaultButton2	' Define buttons.

Title = "MsgBox Demonstration"	' Define title.

Help = "DEMO.HLP"	' Define Help file.

Ctxt = 1000	' Define topic

' context.

' Display message.

Response = MsgBox(Msg, Style, Title, Help, Ctxt)

If Response = vbYes Then	' User chose Yes.

MyString = "Yes"	' Perform some action.

Else	' User chose No.

MyString = "No"	' Perform some action.

End If


RGB Function Example

This example shows how the RGB function is used to return a whole number representing an RGB color value.  It is used for those application methods and properties that accept a color specification.  The object MyObject and its property are used for illustration purposes only.  If MyObject does not exist, or if it does not have a Color property, an error occurs.

Red = RGB(255, 0, 0)	' Return the value for Red.

I = 75	' Initialize offset.

RGBValue = RGB(I, 64 + I, 128 + I) 	' Same as RGB(75, 139, 203).

MyObject.Color = RGB(255, 0, 0)	' Set the Color property of

' MyObject to Red.


SendKeys Statement Example

This example uses the Shell function to run the Calculator application included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to add some numbers and then quit the Calculator.  (To see the example, paste it into a procedure, then run the procedure.  Because AppActivate changes the focus to the Calculator application, you can't single step through the code.)

ReturnValue = Shell("Calc.exe", 1)	' Run Calculator.

AppActivate ReturnValue 	' Activate 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.

SendKeys "%{F4}", True	' Send ALT+F4 to close Calculator.


^ Operator Example

This example uses the ^ operator to raise a number to the power of an exponent.

MyValue = 2 ^ 2	' Returns 4.

MyValue = 3 ^ 3 ^ 3	' Returns 19683.

MyValue = (-5) ^ 3	' Returns -125.


+ Operator Example

This example uses the + operator to sum numbers.  The + operator can also be used to concatenate strings, however, to eliminate ambiguity, you should use the & operator instead.  If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned.  If the components are exclusively strings, the strings are concatenated.

MyNumber = 2 + 2	' Returns 4.

MyNumber = 4257.04 + 98112	' Returns 102369.04.

Var1 = "34": Var2 = 6	' Initialize mixed variables.

MyNumber = Var1 + Var2	' Returns 40.

Var1 = "34": Var2 = "6"	' Initialize variables with strings.

MyNumber = Var1 + Var2	' Returns "346" (string concatenation).


- Operator Example

This example uses the - operator to calculate the difference between two numbers.

MyResult = 4 - 2	' Returns 2.

MyResult = 459.35 - 334.90	' Returns 124.45.


* Operator Example

This example uses the * operator to multiply two numbers.

MyValue = 2 * 2	' Returns 4.

MyValue = 459.35 * 334.90 	' Returns 153836.315.


/ Operator Example

This example uses the / operator to perform floating-point division.

MyValue = 10 / 4	' Returns 2.5.

MyValue = 10 / 3	' Returns 3.333333.


\ Operator Example

This example uses the \ operator to perform integer division.

MyValue = 11 \ 4	' Returns 2.

MyValue = 9 \ 3	' Returns 3.

MyValue = 100 \ 3	' Returns 33.


Mod Operator Example

This example uses the Mod operator to divide two numbers and return only the remainder.  If either number is a floating-point number, it is first rounded to an integer.

MyResult = 10 Mod 5	' Returns 0.

MyResult = 10 Mod 3	' Returns 1.

MyResult = 12 Mod 4.3	' Returns 0.

MyResult = 12.6 Mod 5	' Returns 3.


& Operator Example

This example uses the & operator to force string concatenation.

MyStr = "Hello" & " World"	' Returns "Hello World".

MyStr = "Check " & 123 & " Check"	' Returns "Check 123 Check".


Comparison Operators Example

This example shows various uses of comparison operators, which you use to compare expressions.

MyResult = (45 < 35)	' Returns False.

MyResult = (45 = 45)	' Returns True.

MyResult = (4 <> 3)	' Returns True.

MyResult = ("5" > "4")	' Returns True.

Var1 = "5": Var2 = 4	' Initialize variables.

MyResult = (Var1 > Var2)	' Returns True.

Var1 = 5: Var2 = Empty

MyResult = (Var1 > Var2)	' Returns True.

Var1 = 0: Var2 = Empty

MyResult = (Var1 = Var2)	' Returns True.


And Operator Example

This example uses the And operator to perform a logical conjunction on two expressions.

A = 10: B = 8: C = 6: D = Null	' Initialize variables.

MyCheck = A > B And B > C	' Returns True.

MyCheck = B > A And B > C	' Returns False.

MyCheck = A > B And B > D	' Returns Null.

MyCheck = A And B	' Returns 8 (bit-wise comparison).


Eqv Operator Example

This example uses the Eqv operator to perform logical equivalence on two expressions.

A = 10: B = 8: C = 6: D = Null	' Initialize variables.

MyCheck = A > B Eqv B > C	' Returns True.

MyCheck = B > A Eqv B > C	' Returns False.

MyCheck = A > B Eqv B > D	' Returns Null.

MyCheck = A Eqv B	' Returns -3 (bit-wise comparison).


Imp Operator Example

This example uses the Imp Operator to perform logical implication on two expressions.

A = 10: B = 8: C = 6: D = Null	' Initialize variables.

MyCheck = A > B Imp B > C	' Returns True.

MyCheck = A > B Imp C > B	' Returns False.

MyCheck = B > A Imp C > B	' Returns True.

MyCheck = B > A Imp C > D	' Returns True.

MyCheck = C > D Imp B > A	' Returns Null.

MyCheck = B Imp A	' Returns -1 (bit-wise comparison).


Not Operator Example

This example uses the Not operator to perform logical negation on an expression.

A = 10: B = 8: C = 6: D = Null	' Initialize variables.

MyCheck = Not(A > B)	' Returns False.

MyCheck = Not(B > A)	' Returns True.

MyCheck = Not(C > D)	' Returns Null.

MyCheck = Not A	' Returns -11 (bit-wise comparison).


Or Operator Example

This example uses the Or operator to perform logical disjunction on two expressions.

A = 10: B = 8: C = 6: D = Null	' Initialize variables.

MyCheck = A > B Or B > C	' Returns True.

MyCheck = B > A Or B > C	' Returns True.

MyCheck = A > B Or B > D	' Returns True.

MyCheck = B > D Or B > A	' Returns Null.

MyCheck = A Or B	' Returns 10 (bit-wise comparison).


Xor Operator Example

This example uses the Xor operator to perform logical exclusion on two expressions.

A = 10: B = 8: C = 6: D = Null	' Initialize variables.

MyCheck = A > B Xor B > C	' Returns False.

MyCheck = B > A Xor B > C	' Returns True.

MyCheck = B > A Xor C > B	' Returns False.

MyCheck = B > D Xor A > B	' Returns Null.

MyCheck = A Xor B	' Returns 2 (bit-wise comparison).


Like Operator Example

This example uses the Like operator to compare a string to a pattern.

MyCheck = "aBBBa" Like "a*a"	' Returns True.

MyCheck = "F" Like "[A-Z]"	' Returns True.

MyCheck = "F" Like "[!A-Z]"	' Returns False.

MyCheck = "a2a" Like "a#a"	' Returns True.

MyCheck = "aM5b" Like "a[L-P]#[!c-e]"	' Returns True.

MyCheck = "BAT123khg" Like "B?T*"	' Returns True.

MyCheck = "CAT123khg" Like "B?T*"	' Returns False.


Is Operator Example

This example uses the Is operator to compare two object references.  The object variable names are generic and used for illustration purposes only.

Set YourObject = MyObject	' Assign object references.

Set ThisObject = MyObject

Set ThatObject = OtherObject

MyCheck = YourObject Is ThisObject	' Returns True.

MyCheck = ThatObject Is ThisObject	' Returns False.

' Assume MyObject <> OtherObject

MyCheck = MyObject Is ThatObject	' Returns False.


Chr Function Example

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

MyChar = Chr(65)	' Returns A.

MyChar = Chr(97)	' Returns a.

MyChar = Chr(62)	' Returns >.

MyChar = Chr(37)	' Returns %.


Format Function Example

This example shows various uses of the Format function to format values using both named and user-defined formats.  For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running.  When times and dates are displayed in the development environment, the short time and short date formats of the code locale are used.  When displayed by running code, the short time and short date formats of the system locale are used, which may differ from the code locale.  For this example, English/United States is assumed.

MyTime and MyDate are displayed in the development environment using current system short time and short date settings.

MyTime = #17:04:23#

MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.

MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.

MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")	' Returns "17:4:23".

MyStr = Format(MyTime, "hh:mm:ss AMPM")	' Returns "05:04:23 PM".

MyStr = Format(MyDate, "dddd, mmm d yyyy")	' Returns "Wednesday,

' Jan 27 1993".

' If format is not supplied, a string is returned.

MyStr = Format(23)	' Returns "23".

' User-defined formats.

MyStr = Format(5459.4, "##,##0.00")	' Returns "5,459.40".

MyStr = Format(334.9, "###0.00")	' Returns "334.90".

MyStr = Format(5, "0.00%")	' Returns "500.00%".

MyStr = Format("HELLO", "<")	' Returns "hello".

MyStr = Format("This is it", ">")	' Returns "THIS IS IT".


Hex Function Example

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

MyHex = Hex(5)	' Returns 5.

MyHex = Hex(10)	' Returns A.

MyHex = Hex(459)	' Returns 1CB.


InStr Function Example

This example uses the InStr function to return the position of the first occurrence of one string within another.

SearchString ="XXpXXpXXPXXP"	' String to search in.

SearchChar = "P"	' Search for "P".

' A textual comparison starting at position 4. Returns 6.

MyPos = InStr(4, SearchString, SearchChar, 1)

' A binary comparison starting at position 1. Returns 9.

MyPos = InStr(1, SearchString, SearchChar, 0)

' Comparison is binary by default (last argument is omitted).

MyPos = InStr(SearchString, SearchChar)	' Returns 9.

MyPos = InStr(1, SearchString, "W")	' Returns 0.


LCase Function Example

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

Uppercase = "Hello World 1234"	' String to convert.

Lowercase = LCase(UpperCase)	' Returns "hello world 1234".


Left Function Example

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

AnyString = "Hello World"	' Define string.

MyStr = Left(AnyString, 1)	' Returns "H".

MyStr = Left(AnyString, 7)	' Returns "Hello W".

MyStr = Left(AnyString, 20)	' Returns "Hello World".


Len Function Example

This example uses the Len function to return the number of characters in a string or the number of bytes required to store a variable.  The Type...End Type block defining CustomerRecord must be preceded by the keyword Private if it appears in a Class module.  In a standard module, a Type statement can be Public.  To create a standard module, choose Module from the Insert menu.

Type CustomerRecord	' Define user-defined type.

ID As Integer	' Place this definition in a

Name As String * 10	' standard module.

Address As String * 30

End Type

Dim Customer As CustomerRecord	' Declare variables.

Dim MyInt As Integer, MyCur As Currency

MyString = "Hello World"	' Initialize variable.

MyLen = Len(MyInt)	' Returns 2.

MyLen = Len(Customer)	' Returns 42.

MyLen = Len(MyString)	' Returns 11.

MyLen = Len(MyCur)	' Returns 8.


LSet Statement Example

This example uses the LSet statement to left align a string within a string variable.  Although LSet can also be used to copy a variable of one user-defined type to another variable of a different, but compatible, user-defined type, this practice is not recommended.  Due to the varying implementations of data structures among platforms, such a use of LSet cannot be guaranteed to be portable.

MyString = "0123456789"	' Initialize string.

LSet MyString = "<-Left"	' MyString contains "<-Left    ".


LTrim, RTrim, and Trim Functions Example

This example uses the LTrim and RTrim functions to strip leading and trailing spaces, respectively, from a string variable.  It uses the Trim function alone to strip both types of spaces.

MyString = "  <-Trim->  "	' Initialize string.

TrimString = LTrim(MyString)	' TrimString = "<-Trim->  ".

TrimString = RTrim(MyString)	' TrimString = "  <-Trim->".

TrimString = LTrim(RTrim(MyString))	' TrimString = "<-Trim->".

' Using the Trim function alone achieves the same result.

TrimString = Trim(MyString)	' TrimString = "<-Trim->".


Mid Function Example

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

MyString = "Mid Function Demo"	' Create text string.

FirstWord = Mid(MyString, 1, 3)	' Returns "Mid".

LastWord = Mid(MyString, 14, 4)	' Returns "Demo".

MidWords = Mid(MyString, 5)	' Returns "Function Demo".


Mid Statement Example

This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.

MyString = "The dog jumps"	' Initialize string.

Mid(MyString, 5, 3) = "fox"	' MyString = "The fox jumps".

Mid(MyString, 5) = "cow"	' MyString = "The cow jumps".

Mid(MyString, 5) = "cow jumped over"	' MyString = "The cow jumpe".

Mid(MyString, 5, 3) = "duck"	' MyString = "The duc jumpe".


Oct Function Example

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

MyOct = Oct(4) 	' Returns 4.

MyOct = Oct(8)	' Returns 10.

MyOct = Oct(459)	' Returns 713.


Right Function Example

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

AnyString = "Hello World"	' Define string.

MyStr = Right(AnyString, 1)	' Returns "d".

MyStr = Right(AnyString, 6)	' Returns " World".

MyStr = Right(AnyString, 20)	' Returns "Hello World".


RSet Statement Example

This example uses the RSet statement to right align a string within a string variable.

MyString = "0123456789"	' Initialize string.

RSet MyString = "Right->"	' MyString contains "   Right->".


Space Function Example

This example uses the Space function to return a string consisting of a specified number of spaces.

' Returns a string with 10 spaces.

MyString = Space(10)

' Insert 10 spaces between two strings.

MyString = "Hello" & Space(10) & "World"


Str Function Example

This example uses the Str function to return a string representation of a number.  When a number is converted to a string, a leading space is always reserved for its sign.

MyString = Str(459)	' Returns " 459".

MyString = Str(-459.65)	' Returns "-459.65".

MyString = Str(459.001)	' Returns " 459.001".


StrComp Function Example

This example uses the StrComp function to return the results of a string comparison.  If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.

MyStr1 = "ABCD": MyStr2 = "abcd"	' Define variables.

MyComp = StrComp(MyStr1, MyStr2, 1)	' Returns 0.

MyComp = StrComp(MyStr1, MyStr2, 0)	' Returns -1.

MyComp = StrComp(MyStr2, MyStr1)	' Returns 1.


String Function Example

This example uses the String function to return repeating character strings of the length specified.

MyString = String(5, "*")	' Returns "*****".

MyString = String(5, 42)	' Returns "*****".

MyString = String(10, "ABC")	' Returns "AAAAAAAAAA".


UCase Function Example

This example uses the UCase function to return an uppercase version of a string.

LowerCase = "Hello World 1234"	' String to convert.

UpperCase = UCase(LowerCase)	' Returns "HELLO WORLD 1234".


Ambiguous name detected: <name>

See Also

The identifier conflicts with another identifier or needs qualification.  This error has the following causes and solutions:

More than one object in the same scope may have elements with the same name.

Qualify the element name by including the object name and a period.  For example:

object.property

Module-level identifiers) may be reused in a procedure (although it makes programs harder to maintain and debug).  However, if you want to refer to both items in the same procedure, the item having wider scope must be qualified.  For example, if MyID is declared at the module level of MyModule, and then a procedure-level variable is declared with the same name in the module, references to the module-level variable must be appropriately qualified:

Dim MyID As String

Sub MySub

MyModule.MyID = "This is module-level variable"

Dim MyID As String

MyID = "This is the procedure-level variable"

Debug.Print MyID

Debug.Print MyModule.MyID

End Sub

An identifier declared at module level conflicts with a procedure name.  For instance, this error occurs if the variable MyID is declared at module level, and then a procedure is defined with the same name:

Public MyID

Sub MyID

. . .

End Sub

In this case, change one of the names because modification with a common module name would not resolve the ambiguity.  Note that procedure names are Public by default, but variable names are Private unless specified as Public.

For additional information, select the item in question and press F1.


See Also

Public Statement

Private Statement

Resolving Naming Conflicts


Argument in ParamArray may not be named

See Also

Arguments to a ParamArray must be positional.  This error has the following cause and solution:

Named-argument syntax appears in a procedure call.

The named-argument syntax cannot be used with position-only arguments like those in a ParamArray.  To supply only some of the elements of the ParamArray, use commas as placeholders for those you want to omit.  For example, in the following call, if the ParamArray arguments begin after Arg2, values are being passed only for the first, third, and sixth values in the ParamArray:

MySub Arg1, Arg2, 7,, 44,,,3

Note   The ParamArray always represents the last items in the argument list.

For additional information, select the item in question and press F1.


See Also

ParamArray Keyword


Argument not optional (Error 449)

See Also

The number and types of arguments must match those expected.  This error has the following causes and solutions:

Incorrect number of arguments.

Supply all necessary arguments.  For instance, the Left function requires two arguments, the first representing the character string being operated on, and the second representing the number of characters to return from the left side of the string.  Because neither argument is optional, both must be supplied.

Omitted argument is not optional.

An argument can only be omitted from a call to a user-defined procedure if it was declared Optional in the procedure declaration.  Either supply the argument in the call, or declare the parameter Optional in the definition.

For additional information, select the item in question and press F1.


See Also

Left Function

Optional Keyword


Argument required for Property Let or Property Set

See Also

The purpose of Property Let and Property Set procedures is to give a new value to a property.  This error has the following causes and solutions:

In setting the property, the value does not appear in the right place.

Place the value to which the property is to be set on the right-hand side of the expression setting the property value.

In the procedure definition, the parameter defined to receive the value passed on the right-hand side of the expression is missing or misplaced.

Specify a parameter for the value argument list of the definition of the procedure.  If the procedure takes more than one argument, the property-value parameter must appear last in the list.

For additional information, select the item in question and press F1.


See Also

Property Let Statement

Property Set Statement


Array already dimensioned

See Also

A static array can only be dimensioned once.  This error has the following causes and solutions:

You attempted to change the dimensions of a static array with a ReDim statement [image] only dynamic arrays can be redimensioned.

Either remove the redimensioning, or use a dynamic array.  To define a dynamic array, use a Dim, Public, Private, or Static statement with empty parentheses.  For example:

Dim MyArray()

In a procedure, you can define a dynamic array with the ReDim or Static statement using a variable for the number of elements:

ReDim MyArray(n)

An Option Base statement occurs after array dimensions are set.

Make sure any Option Base statement precedes all array declarations.

For additional information, select the item in question and press F1.


See Also

Dim Statement

Option Base Statement

Private Statement

Public Statement

ReDim Statement

Static Statement


Array argument must be ByRef

See Also

Arrays declared with Dim, ReDim, or Static cannot be passed ByVal.  This error has the following cause and solution:

You tried to pass a whole array ByVal.

An individual element of an array can be passed ByVal (by value), but a whole array must be passed ByRef (by reference).  Note that ByRef is the default.  If you have an array you must pass ByVal, and you want to do so to prevent changes to the array's elements from being propagated back to the caller, you can pass the array argument in its own set of parentheses, or you can place it into a Variant, then pass the Variant to the ByVal parameter, as follows:

Dim MyVar As Variant

MyVar = OldArray()

For additional information, select the item in question and press F1.


See Also

ByRef Keyword

ByVal Keyword

Dim Statement

ReDim Statement

Static Statement

Variant Data Type


Bad DLL calling convention (Error 49)

See Also

Arguments passed to a dynamic-link library (DLL) routine must exactly match those expected by the routine.  Calling conventions deal with number, type, and order of arguments.  This error has the following causes and solutions:

Your program is calling a routine in a DLL that is being passed the wrong type of arguments.

Make sure all argument types agree with those specified in the declaration of the routine you are calling.

Your program is calling a routine in a DLL that either is being passed the wrong number of arguments.

Make sure you are passing the same number of arguments indicated in the declaration of the routine you are calling.

Your program is calling a routine in a DLL, but is not using the Pascal calling convention.

If the DLL routine expects arguments by value, then make sure ByVal is specified for those arguments in the declaration for the routine.

For additional information, select the item in question and press F1.


See Also

ByVal Keyword


Bad file mode (Error 54)

See Also

Statements used in manipulating file contents must be appropriate to the mode in which the file was opened.  This error has the following causes and solutions:

A Put or Get statement is specifying a sequential file.

Put and Get can only refer to files opened for Random or Binary access.

A Print # statement specifies a file opened for an access mode other than Output or Append.

Use a different statement to place data in the file, or reopen the file in an appropriate mode.

An Input # statement specifies a file opened for an access mode other than Input.

Use a different statement to place data in the file, or reopen the file in Input mode.

You have attempted to write to a read-only file.

Change the read/write status of the file or don't try to write to it.

For additional information, select the item in question and press F1.


See Also

Get Statement

Input # Statement

Open Statement

Print # Statement

Put Statement


Bad file name or number (Error 52)

See Also

An error occurred trying to access the specified file.  This error has the following causes and solutions:

A statement refers to a file with a file number or filename that is:

Not specified in the Open statement or was specified in an Open statement, but has since been closed:

Specify the filename in an Open statement.  Note that if you invoked the Close statement without arguments you may have inadvertently closed all currently open files, invalidating all file numbers.

Out of the range of file numbers (1 [image] 511).

If your code is generating file numbers algorithmically, make sure the numbers are valid.

There is an invalid name or number.

Filenames must conform to operating system conventions as well as Basic file-naming conventions.  In Microsoft Windows (version 3.1 and earlier), 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:

Character	Description

.	Period

"	Quotation mark

'	Single quotation mark (apostrophe)

+	Plus sign

/	Slash

\	Backslash

[ ]	Brackets

:	Colon

;	Semicolon

|	Vertical bar

=	Equal sign

,	Comma

The name should not contain any spaces.  The following names are reserved and can't be used for files or directories:  CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL.  For instance, if you try to name a file PRN in an Open statement, the default printer will simply become the destination for Print # and Write # statements directed to the file number specified in the Open statement.

The following are examples of valid Microsoft Windows filenames (version 3.1 and earlier):

LETTER.DOC

MEMO.TXT

BUDGET.92

12345678.901

2NDTRY.RPT

1

For additional information, select the item in question and press F1.


See Also

Chr Function

Open Statement

Print # Statement

Write # Statement


Bad record length (Error 59)

See Also

The length of a record variable in a Get or Put statement must be the length specified in its corresponding Open statement.  This error has the following causes and solutions:

The record variable's length differs from the length specified in the corresponding Open statement.

Make sure the sum of the sizes of fixed-length variables in the user-defined type defining the record variable's type is the same as the value stated in the Open statement's Len clause.  In the following example, assume RecVar is a variable of the appropriate type; you can use the Len function to specify the length, as follows:

Open MyFile As #1 Len = Len(RecVar)

The variable in a Put statement is (or includes) a variable-length string.

Because a two-byte descriptor is always added to a variable-length string placed in a random access file with Put, the variable-length string must be at least two characters shorter than the record length specified in the Len clause of the Open statement.

The variable in a Put statement is (or includes) a Variant.

Like variable-length strings, Variant data types also require a two-byte descriptor.  Variants containing variable-length strings require a four-byte descriptor.  Therefore, for variable-length strings in a Variant, the string must be at least four bytes shorter than the record length specified in the Len clause.

For additional information, select the item in question and press F1.


See Also

Get Statement

Put Statement

Open Statement

String Data Type

Variant Data Type


Bad record number (Error 63)

See Also

An error occurred during the attempted file access.  This error has the following cause and solution:

The record number in a Put or Get statement is less than or equal to zero.

Check the calculations used in generating the record number.  Make sure that the variables containing the record number or used in calculating record numbers are spelled correctly, since a misspelled variable name is implicitly declared and initialized to zero unless you have properly placed Option Explicit in the module.

For additional information, select the item in question and press F1.


See Also

Get Statement

Option Explicit Statement

Put Statement


Beginning of search scope has been reached; do you want to continue from the end?

Your search was unsuccessful.  This condition has the following cause and solution:

Your upward search has reached the beginning of the specified scope.

You can choose to continue searching from the end of the search scope, or cancel and change the scope of the search.


Block If without End If

See Also

An error occurred due to an incomplete statement.  This error has the following cause and solution:

An If statement is used without a corresponding End If statement.

A multiline If statement must terminate with a matching End If.  For nested If...End If statements, make sure there is a correctly matched If...End If structure inside each enclosing If...End If structure.

For additional information, select the item in question and press F1.


See Also

If...Then...Else Statement


Breakpoint not allowed on this line

See Also

Breakpoints can only be placed on certain parts of statements.  This error has the following causes:

You tried to place a breakpoint on a line that cannot accept a breakpoint, for example, one of the following:

A line that comprises only comments.

A line that comprises only line labels.

A line that contains only declarations (Const, Dim, Static, Type, and so on).

Any line in a hidden module.

Any line in the Immediate pane.

For additional information, select the item in question and press F1.


See Also

Select Case Statement


ByRef argument type mismatch

See Also

An argument passed by reference (ByRef, the default), must have the precise data type expected in the procedure. This error has the following cause and solution:

You passed an argument of one type that could not be coerced to the type expected.

For example, if you try to pass an Integer variable when a Long is expected, this error occurs.  If you want coercion to occur, even if it causes information to be lost, you can pass the argument in its own set of parentheses.  For example, to pass the Variant argument MyVar to a procedure that expects an integer argument, you could write the call as follows:

Dim MyVar

MyVar = 3.1415

Call SomeSub((MyVar))

Sub SomeSub (MyNum As Integer)

MyNum = MyNum + MyNum

End Sub

Placing the argument in its own set of parentheses forces evaluation of it as an expression.  During this evaluation, the fractional portion of the number is rounded (not truncated) to make it conform to the expected argument type.  The result of the evaluation is placed in a temporary location, and a reference to the temporary location is received by the procedure.  Thus, the original MyVar retains its value.

Note   If you do not specify a type for a variable, the variable receives the default type, Variant.  This is not always obvious. For example, the following code declares two variables, the first, MyVar, is a Variant; the second, AnotherVar, is an Integer.

Dim MyVar, AnotherVar As Integer

For additional information, select the item in question and press F1.


See Also

ByRef Keyword

ByVal Keyword

Integer Data Type

Long Data Type

Variant Data Type


Can't assign array of fixed-length string or user-defined type to Variant

See Also

A Variant can only accept assignment of data having a valid VarType.  This error has the following causes and solutions:

You tried to assign an array of fixed-length strings to a Variant variable.  When a single fixed-length string is assigned to a Variant, it is coerced to a variable-length string, but this cannot be done for an array of fixed-length strings.

If you must have the array in a variant, use a loop to assign the individual elements of the array to the elements of a temporary array of variable-length strings. You can then assign the array to the variant, and use Erase to deallocate the temporary array.  Note, however, that you cannot deallocate a fixed-size array with Erase.

You tried to pass a fixed-length string or user-defined type to the VarType or TypeName function.

An argument to the VarType or TypeName function must be a valid Variant type.

You tried to assign a user-defined type to a Variant variable.

Although you cannot directly assign a whole variable of user-defined type to a Variant, you can use the Array function to assign the individual elements of a variable of user-defined type to a Variant.  This would produce a Variant containing an array of variants.  The VarType of each element in this array of variants would correspond to the original type of each element of the user-defined type.

You tried to pass an array of fixed-length strings or user-defined types as an argument in a procedure call that requires a Variant argument.  Note that any time a procedure is late bound (that is, when the call must be constructed at run time), all arguments must be passed as Variant types.  For example, the following code causes this error:

Dim MyForm As Object	' Because MyForm is Object, binding is late.

Set MyForm = New Form1

Dim StringArray(10) As String * 12

' The next line generates the error.

MyForm.MyProc StringArray

For the string array, use a loop to assign each individual member of the array to a temporary array of variable-length strings. You can then assign that array to a Variant to pass to the procedure.  For an array of user-defined types, you can use the Array function to assign the individual elements of a variable of user-defined type to a Variant.  This produces a Variant containing an array of variants.  The VarType of each element in this array of variants corresponds to the original type of each element of the user-defined type.

For additional information, select the item in question and press F1.


See Also

Array Function

Erase Statement

TypeName Function

Variant Data Type

VarType Function


Can't assign to an array

See Also

Each element of an array must have its value assigned individually.  This error has the following causes and solutions:

You inadvertently tried to assign a single value to an array variable without specifying which element the value should be assigned to.

To assign to an array element, you must specify the element in a subscript.  For example, if MyArray is an integer array, the expression MyArray = 5 is invalid, but the following expression is valid:

MyArray(UBound(MyArray)) = 5

You tried to assign a whole array to another array.  For example, if Arr1 is an array and Arr2 is another array, the following two assignments are both invalid:

Arr1 = Arr2	' Invalid assignment.

Arr1() = Arr2()	' Invalid assignment.

To assign one array to another, you must individually assign the elements.  For example:

For count = LBound(Arr2) to UBound(Arr2)

Arr1(count) = Arr2(count)

Next count

Note that you can place a whole array to a Variant, resulting in a single variant variable containing the whole array:

Dim MyArr As Variant

MyVar = Arr2()

You then reference the elements of the array in the variant with the same subscript notation as for a normal array, for instance:

MyVar(3) = MyVar(1) + MyVar(5)

For additional information, select the item in question and press F1.


See Also

Variant Data Type

VarType Function


Can't change data types of array elements

See Also

ReDim can only be used to change the number of elements in an array.  This error has the following cause and solution:

You tried to redeclare the data type of an array using ReDim.

Declare a new array of the type you want, then use the conversion functions to assign each element of the old array to the corresponding element of the new array.

You can also place the array in a Variant variable.  This can be done with a simple assignment:

Dim MyVar As Variant

MyVar = MyIntegerArray()

This creates a Variant containing an array tagged as the type of the original array.  You can then assign variables of any valid VarType to the elements of the array within a variant.

For additional information, select the item in question and press F1.


See Also

ReDim Statement

TypeName Function

Variant Data Type

VarType Function


Can't display hidden procedure

Everything in a hidden module is hidden.  This error has the following cause and solution:

You tried to view a procedure in a hidden module.

Unhide the module to view the procedure.  If you are trying to view a line that generated an error in a hidden procedure, run the code again (after unhiding the module) to view the error.

For additional information, select the item in question and press F1.


$#Can't edit module

Modules marked as protected can be viewed, but not edited.  This error has the following cause and solution:

You tried to edit a protected module.

Remove the protection from the module, then try editing again.

For additional information, select the item in question and press F1.


Can't find project or library

You cannot run your code until all missing references are resolved.  This error has the following causes and solutions:

A referenced object library could not be found.

Unresolved references are prefixed with "MISSING:" in the References dialog box.  Select the missing reference to display the path and language of the missing library.  Follow these steps to resolve the reference or references:

To resolve the references

1.	Choose References from the Tools menu.

2.	Select the missing reference.

3.	Choose Browse to open the Browse dialog box.

4.	Use the Browse dialog box to find the missing reference.

5.	Click OK.

6.	Repeat the preceding steps until all missing references are resolved.

Once you find a missing item, the "MISSING:" prefix is removed to indicate that the link is reestablished.

To remove references that are no longer needed, simply clear the checkbox beside the unneeded reference.  Note that the references to the Visual Basic object library (VAXXX.OLB or VAXXXX.OLB) cannot be removed.

Applications may support different language versions of their object libraries.  To find out which language version is required, click the reference, and check the language indicated at the bottom of the dialog box.

Object libraries exist in different versions for each platform.  Therefore, when projects are moved across platforms, the correct language version of the referenced library (for that platform) must be available in the location specified in your application documentation.

Object library filenames are generally constructed as follows:

Windows (version 3.1 and earlier):   Application Code + Language Code + [Version].OLB.  For example:

VAFR2.OLB would be the object library for French Visual Basic for applications, Version 2.

XLFR50.OLB would be the French Microsoft Excel 5.0 object library.

For example:

VA FR 2 OLB would be the object library for French Visual Basic for applications, Version 2.

MS Excel FR 50 OLB would be the French Microsoft Excel 5.0 object library.

If you cannot find a missing  library on your system, and the  missing library is a Microsoft application object library, you can obtain it as follows:

If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file.  Under electronic services, you will find instructions on how to use the appropriate service option.

If you do not have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft.  Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.

Note   Visual Basic version 4 doesn't support multiple projects.

For additional information, select the item in question and press F1.


Can't Get or Put an object reference variable or a variable of user-defined type containing an object reference

See Also

An object reference is temporary and can easily become invalid between closing and opening a file.  This error has the following cause and solution:

The variable in your Get or Put statement contains, or is declared to contain, a reference to an object.  If the variable is an object reference you can't use it with Get and Put statements.  If you meant to place the value of all (or some) of the object's properties in the file, each property must be individually specified.

The user-defined [image] type variable in your Get or Put statement contains an element that is an object reference.

If the variable's Type statement contains an element representing an object (for example, it is defined in a class module, has Object data type, is a form or a control, and so on) remove it from the definition, or define a new type for use with the Get and Put statements that has no Object type element in its definition.

If you have elements in the user-defined type with Variant type, make sure no object reference is being assigned to that element.  A Variant can accept such an assignment, but will cause this error if its user-defined type is used in a Get or Put.

Note that you can use Input #, Line Input #, Print #, or Write # to write the default property of an object to disk.

For additional information, select the item in question and press F1.


See Also

Get Statement

Input # Statement

Line Input # Statement

Object Data Type

Print # Statement

Put Statement

Type Statement

Variant Data Type

Write # Statement


Can't load module; invalid format

A module must be in text format.  This error has the following cause and solution:

You attempted to load a binary format file as a module.

Some versions of Visual Basic permit you to save code in both binary and text formats.  If possible, reload the file in the application in which it was last saved and save it as text.

For additional information, select the item in question and press F1.


Can't perform requested operation (Error 17)

An operation cannot be carried out if it would invalidate the current state of the project.  This error has the following cause and solution:

The requested operation would invalidate the current state of the project.  For example, the error occurs if you use the References dialog box of the Tools menu to add a reference to a new object library while a program is in break mode.

Choose End from the Run menu to stop execution of the current code, then retry the operation.

An attempt was made to programmatically modify currently running code.  For example, your code may have tried to read code from a disk file into a currently running module.

Although you can modify modules in the project while they are not actually running, you cant make modifications to a running module.  To make such changes, you must stop the module from running, make the additions or changes, and then restart execution.

For additional information, select the item in question and press F1.


Can't record into running module

You must end execution to begin recording.  This error has the following cause and solution:

You tried to record a macro while executing module code.

Stop execution by choosing End from the Run menu or pressing CTRL+BREAK, then turn on recording.

For additional information, select the item in question and press F1.


Can't rename with different drive (Error 74)

See Also

The Name statement must rename the file to the current drive.  This error has the following cause and solution:

You tried to move a file to a different drive using the Name statement.

Use FileCopy to write the file to another drive, and delete the old file with a Kill statement.

For additional information, select the item in question and press F1.


See Also

FileCopy Statement

Kill Statement

Name Statement


Case Else outside Select Case

See Also

A Case Else can only occur between matching Select Case and End Select statements.  This error has the following cause and solution:

You placed a Case Else statement outside the Select Case...End Select block.

Move the Case Else within a Select Case...End Select block.

For additional information, select the item in question and press F1.


See Also

Select Case Statement


Case without Select Case

See Also

A Case statement must occur within a Select Case...End Select Block.  This error has the following cause and solution:

A Case statement could not be matched with a preceding 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...End Select structure generates this error.

For additional information, select the item in question and press F1.


See Also

If...Then...Else Statement

Select Case Statement


Circular dependencies between modules

See Also

Circular references between modules, constants, and user-defined types are not allowed.  This error has the following cause and solution:

A user-defined type or constant in one module references a user-defined type or constant in a second module, which in turn references another user-defined type or constant in the first module.

Remove the dependent references.

For additional information, select the item in question and press F1.


See Also

Const Statement

Type Statement

Visual Basic Constants


Class doesn't support OLE Automation (Error 430)

See Also

Not all objects expose an OLE Automation interface.  This error has the following cause and solution:

The class you specified in the GetObject or CreateObject function call was found, but has not exposed a programmability interface.

You can't write code to control an object's behavior unless it has been exposed for OLE automation.  Check the documentation of the application that created the object for limitations on the use of OLE Automation with this class of object.

For additional information, select the item in question and press F1.


See Also

CreateObject Function

GetObject Function

OLE Automation


Code execution has been interrupted

Code execution can be suspended when necessary.  This condition has the following cause and solution:

A CTRL+BREAK (Microsoft Windows), ESC (Microsoft Excel) key combination has been encountered.

From the dialog box, choose either Debug to enter break mode, Continue to resume, or End to stop execution.

For additional information, select the item in question and press F1.


Compile error in hidden module: <module name>

A protected module cannot be displayed.  This error has the following cause and solution:

There is a compilation error in the code of the specified module, but it can't be displayed because the project is protected.

Unprotect the project, then run the code again to view the error.

For additional information, select the item in question and press F1.


Constant expression required

See Also

A constant must be initialized.  This error has the following causes and solutions:

You tried to initialize a constant with a variable, an instance of a user-defined type, an object, or the return value of a function call.

Initialize constants with literals, previously declared constants, or literals and constants joined by operators (except the Is logical operator).

You tried to declare an array using a variable to specify the number of elements.

To declare a dynamic array within a procedure, declare the array with ReDim and specify the number of elements with a variable.

For additional information, select the item in question and press F1.


See Also

Is Operator

ReDim Statement


Current module does not support Print method

See Also

Not all methods and properties are appropriate in all modules.  This error has the following causes and solutions:

You tried to use the Print method on an object that cannot display anything.  For example, you cannot use the Print method without qualification in a standard module.

Remove the reference to the Print method, or qualify it with an appropriate object.  For example, qualify it with the Debug object to display its arguments in the Immediate pane during debugging.

You tried to use the Line, Circle, PSet, or Scale method on an object that cannot accept them.  For example, they cannot appear unqualified in a standard module or an OLE Automation class module.

For additional information, select the item in question and press F1.


See Also

Debug Object

Print Method


Cyclic reference of projects not allowed

Circular references to projects are not allowed.  For example, if MyProj references YourProj, then YourProj (or a project that references YourProj) can't reference MyProj.  This error has the following cause and solution:

You tried to add a reference to a project that is already part of the project.

Remove the circular reference or references.

Note   Visual Basic version 4 doesn't support multiple projects.

For additional information, select the item in question and press F1.


Deftype statements must precede declarations

See Also

Deftype statements include DefInt, DefDbl, DefCur, and so on.  This error has the following causes and solutions:

A variable declaration precedes a Deftype statement at module level.

Move the Deftype statement to precede all variable declarations.

A Deftype statement appears in a procedure.

Move the Deftype statement to module level, preceding all variable declarations.

For additional information, select the item in question and press F1.


See Also

Deftype Statements


Destination label too far away; loop, Select Case, or block If too large

See Also

Procedures can be as large as 64K from beginning to end, but because branching can occur either forward or backward within a procedure, such branching is limited to 32,767 bytes in either direction.  This error has the following causes and solutions:

You have a branching statement (GoTo, GoSub) whose destination label is farther away than 32,767 bytes from the source branching statement.

Move the label closer, or make the procedure smaller.

You have a very large loop structure that occupies more than 32K of memory from beginning to end.

Make the loop smaller.

You have a very large block If structure that contains a Then or Else clause that occupies more than 32K of memory from beginning to end.

Reduce the size of the offending portion of the structure.

For additional information, select the item in question and press F1.


See Also

GoSub Statements

GoTo Statements

If...Then...Else Statements


Device I/O error (Error 57)

External devices are sometimes subject to unanticipated errors.  This error has the following cause and solution:

An input or output error occurred while your program was using a device such as a printer or disk drive.

Make sure the device is operating properly, then retry the operation.

For additional information, select the item in question and press F1.


Device unavailable (Error 68)

This error has the following causes and solutions:

The device you are trying to access either is either not online or does not exist.

Check power to the device and any cables connecting your computer to the device.  If you are trying to access a printer over a network, make sure there is a logical connection between your computer and the printer, for example, a connection associating LPT1 with the network printer ID.

Your network connection may have been broken.

Reconnect to the network and try the operation again.

For additional information, select the item in question and press F1.


Disk full (Error 61)

See Also

This error has the following causes and solutions:

There is not enough room on the disk for the completion of a Print #, Write #, or Close operation.

Move some files to another disk, or delete some files.

There is not enough room on the disk to create required files.

Move some files to another disk, or delete some files.

For additional information, select the item in question and press F1.


See Also

Close Statement

Print # Statement

Write # Statement


Disk not ready (Error 71)

This error has the following causes and solutions:

There is no disk in the specified drive.

Put a disk in the drive, and retry the operation.

The drive door of the specified drive is open.

Close the drive door, and retry the operation.

For additional information, select the item in question and press F1.


Division by zero (Error 11)

Division by zero is not possible.  This error has the following cause and solution:

The value of an expression being used as a divisor is zero.

Check the spelling of variables in the expression.  A misspelled variable name can implicitly create a numeric variable that is initialized to zero.  Check previous operations on variables in the expression, especially those passed into the procedure as arguments from other procedures.

For additional information, select the item in question and press F1.


Do without Loop

See Also

Each Do must be matched with a terminating Loop.  This error has the following cause and solution:

A Do statement was 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 generate this error.

For additional information, select the item in question and press F1.


See Also

Do...Loop Statement

If...Then...Else Statement


Duplicate declaration in current scope

See Also

The specified name is already used at this level of scope.  For example, two variables can have the same name if they are defined in different procedures, but not if they are defined within the same procedure.  This error has the following causes and solutions:

A new variable or procedure has the same name as an existing variable or procedure.  For example:

Sub MySub()

Dim A As Integer

Dim A As Variant

. . .	' Other declarations or procedure code here.

End Sub

Check the current procedure or module,  and remove any duplicate declarations.

A Const statement uses the same name as an existing variable or procedure.

Remove or rename the constant in question.

You declared a fixed array more than once.

Remove or rename one of the arrays.

Choose Find from the Edit menu to locate the duplicate name.  When specifying the name to search for, omit any type-declaration character, if there is one, because a conflict occurs if the names are the same and the type-declaration characters are different.

Note that a module-level variable can have the same name as a variable declared in a procedure, but when you want to refer to the module-level variable within the procedure, you must qualify it with the module name.  Module names also be reused as variable names within procedures, and can also be qualified.

For additional information, select the item in question and press F1.


See Also

Const Statement

Dim Statement

Erase Statement

ReDim Statement


Duplicate definition

You can only define a conditional compiler constant to have one value. This error has the following cause and solution:

You specified two different values for the same conditional compiler constant, for example:

#Const Mac = 0

#Const Mac = 1

Remove one of the definitions.

For additional information, select the item in question and press F1.


Duplicate Deftype statement

See Also

Deftype statements in the same scope must specify unique letter ranges.  This error has the following cause and solution:

Part or all of the letter range for this Deftype statement is already included in another Deftype statement.

Rewrite the statement so there is no overlap in the letter ranges.

For additional information, select the item in question and press F1.


See Also

Deftype Statements


Duplicate Option statement

See Also

Only one Option statement of each kind may occur in each module.  This error has the following cause and solution:

You've defined more than one Option Base, Option Compare, Option Explicit, or Option Private statement in this module.

Remove any duplicates in the module.

For additional information, select the item in question and press F1.


See Also

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement


Edit can't be undone--proceed anyway?

You will not be able to choose the Undo command to restore the current state after you perform this edit.  This error has the following cause and solution:

This typically occurs when an edit is simply too large to be saved.

Try performing the edit in smaller increments.

For additional information, select the item in question and press F1.


Else without If

See Also

An Else must be preceded by an If.  This error has the following cause and solution:

An Else statement was used without a corresponding If statement.

Check other control structures within the If...End If structure and verify that they are correctly matched.  Also check that the block If is correctly formatted.

For additional information, select the item in question and press F1.


See Also

If...Then...Else Statement

Do...Loop Statement


Empty watch expression

The Add Watch dialog box requires entry of an expression.  This error has the following cause and solution:

You did not supply a watch expression in the Add Watch dialog box.

Add an expression to the Add Watch dialog box or press the ESC key.

For additional information, select the item in question and press F1.


End If without block If

See Also

An End If statement must have a corresponding If statement.  This error has the following cause and solution:

The If clause was omitted or is separated from the End If.

Check other control structures within the If...End If structure and verify that they are correctly matched.  Also check that the block If is correctly formatted.

For additional information, select the item in question and press F1.


See Also

If...Then...Else Statement

Do...Loop Statement


End of search scope has been reached; do you want to continue from the beginning?

Your search was unsuccessful.  This error has the following cause and solution:

Your downward search has reached the end of the specified scope.

You can choose to continue searching from the beginning of the search scope, or cancel and change the scope of the search.


End Select without Select Case

See Also

End Select must be matched with a preceding Select Case.  This error has the following cause and solution:

You used an End Select statement without a corresponding Select Case statement.

This is usually due to an extra End Select below a Select Case block, or leaving behind the End Select statement when copying a Select Case block from one procedure to another.  Check each End Select statement to make sure it terminates a Select Case structure.

For additional information, select the item in question and press F1.


See Also

Select Case Statement


End With without With

See Also

End With must be matched with a preceding With.  This error has the following cause and solution:

You used an End With statement without a corresponding With statement.

Check other control structures within the With...End With structure and verify that they are correctly matched.  For example, an If without a matching End If inside the With...End With structure can cause this error.

For additional information, select the item in question and press F1.


See Also

If...Then...Else Statement

With Statement


Error accessing the system registry

Some operations need to access your system's registration database.  This error has the following cause and solution:

The registration database for your system has been corrupted.

Run the Setup program again.

For additional information, select the item in question and press F1.


Error in loading DLL (Error 48)

See Also

A dynamic link library (DLL) is a library specified in the Lib clause of a Declare statement.  This error has the following causes and solutions:

The file is not DLL-executable.

If the file is a source-text file, it must be compiled and linked to DLL executable form.

The file is not a Microsoft Windows DLL.

Obtain the Microsoft Windows DLL equivalent of the file.

The file is an old Microsoft Windows DLL that is incompatible with Microsoft Windows protect mode.

Obtain an updated version of the DLL.

The DLL references another DLL that is not present.

Obtain the referenced DLL and make it available to the other DLL.

The DLL or one of the referenced DLLs is not in a directory specified by your path.

Move the DLL to a referenced directory, or place its current directory on the path.

For additional information, select the item in question and press F1.


See Also

Declare Statement


Exit Do not within Do...Loop

See Also

Exit Do is only valid within a Do...Loop statement.  This error has the following cause and solution:

You used an Exit Do statement outside a Do...Loop statement.

Make sure a valid Do statement precedes the Exit Do.

For additional information, select the item in question and press F1.


See Also

Do...Loop Statement

Exit Statement


Exit For not within For...Next

See Also

Exit For is only valid within a For...Next loop.  This error has the following cause and solution:

You used an Exit For statement outside a For...Next statement.

Make sure a valid For statement precedes the Exit For.

For additional information, select the item in question and press F1.


See Also

Exit Statement

For...Next Statement


Exit Function not allowed in Sub or Property

See Also

An Exit must match the procedure in which it occurs.  This error has the following cause and solution:

You used an Exit Function in a Sub or Property procedure.

Use Exit Sub or Exit Property for these types of procedure.

For additional information, select the item in question and press F1.


See Also

Exit Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Exit Property not allowed in Function or Sub

See Also

An Exit must match the procedure in which it occurs.  This error has the following cause and solution:

You used Exit Property in a Sub or Function procedure.

Use the proper Exit statement for this type of procedure.

For additional information, select the item in question and press F1.


See Also

Exit Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Exit Sub not allowed in Function or Property

See Also

An Exit must match the procedure in which it occurs.  This error has the following cause and solution:

You used Exit Sub in a Function or Property procedure.

Use the proper Exit statement for this type of procedure.

For additional information, select the item in question and press F1.


See Also

Exit Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected array

See Also

A variable name with a subscript indicates the variable is an array.  This error has the following cause and solution:

The syntax you specified is appropriate for an array, but no array with this name is in scope.

Check to make sure the name of the variable is spelled correctly.  Unless the module contains Option Explicit, a variable is created on first use.  If you misspell the name of an array variable, the variable may be created, but not as an array.

For additional information, select the item in question and press F1.


See Also

Option Explicit Statement


Expected End Function

See Also

An End procedure statement must match the procedure in which it occurs.  This error has the following cause and solution:

You used End Property or End Sub to end a Function procedure.

Use End Function for this type of procedure.

For additional information, select the item in question and press F1.


See Also

End Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected End Property

See Also

An End procedure statement must match the procedure in which it occurs.  This error has the following cause and solution:

You used End Function or End Sub to end a Property procedure.

Use End Property for this type of procedure.

For additional information, select the item in question and press F1.


See Also

End Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected End Sub

See Also

An End procedure statement must match the procedure in which it occurs.  This error has the following cause and solution:

You used End Function or End Property to end a Sub procedure.

Use End Sub for this type of procedure.

For additional information, select the item in question and press F1.


See Also

End Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected End With

See Also

A With block must be terminated.  This error has the following cause and solution:

You did not properly terminate a With block.

Place an End With at the end of the block.

For additional information, select the item in question and press F1.


See Also

End Statement

With Statement


Expected Function or variable

See Also

The syntax of your statement indicates a variable or function call.  This error has the following cause and solution:

The name is not that of a known variable or Function procedure.

Check the spelling of the name.  Also, make sure that any variable or function with that name is visible in the portion of the program from which you are referencing it.  For example, if the function is defined as Private or the variable is not defined as Public, it is only visible within its own module.

You are trying to inappropriately assign a value to a procedure name.  For example if MySub is a Sub procedure, the following code generates this error:

MySub = 237	' Causes Expected Function or variable error

Although you can use assignment syntax with a Property Let procedure or with a Function that returns an object or a Variant containing an object, you cannot use assignment syntax with a Sub, Property Get, or Property Set procedure.

For additional information, select the item in question and press F1.


See Also

Function Statement

Private Statement

Property Get Statement

Public Statement


Expected procedure, not module

See Also

There is no procedure by this name in the current scope, but there is a module by this name.  You can call a procedure, but not a module.  This error has the following cause and solution:

The name of a module is used as a procedure call.

Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected procedure, not project or library

See Also

There is no procedure by this name in the current scope, but there is a project by this name.  You can call a procedure, but not a project.  This error has the following cause and solution:

The name of a project is used as a procedure call.

Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected procedure, not user-defined type

See Also

There is no procedure by this name in the current scope, but there is a user-defined type by this name.  You can call a procedure, but not a user-defined type.  This error has the following cause and solution:

The name of a user-defined type is used as a procedure call.

Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected procedure, not variable

See Also

There is no procedure by this name in the current scope, but there is a variable by this name.  You can call a procedure, but not a variable.  This error has the following cause and solution:

The name of a variable is used as a procedure call.

The error may also be caused by misspelling the name of a valid procedure, because that can be misconstrued as an implicitly defined variable.  Check the spelling of the procedure name, and make sure the procedure you are trying to call is not private to another module.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected Sub or Function, or Property

See Also

The syntax of your statement indicates a Sub, Function, or Property procedure invocation.  This error has the following cause and solution:

The specified name is not that of a Sub, Function, or Property procedure in scope in this part of your program.

Check the spelling of the name.  Note that if the procedure is defined as Private, it can only be called from within its module.

For additional information, select the item in question and press F1.


See Also

Call Statement

Function Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected user-defined type, not project

See Also

There is no user-defined type by this name in the current scope, but there is a project by this name.  You can define a variable as having user-defined type, but not project type.  This error has the following cause and solution:

The name of a project is used as a user-defined type.

Check the spelling of the name of the user-defined type, and make sure the user-defined type is not private to another module.

For additional information, select the item in question and press F1.


See Also

Type Statement

User-Defined Data Type


Expected variable or procedure, not module

See Also

There is no variable or procedure by this name in the current scope, but there is a module by this name. This error has the following cause and solution:

The name of a module is used as a variable or procedure.

Check the spelling of the variable or procedure name, and make sure the name you want to refer to is not private to another module.  A module name can be a qualifier, but can't stand alone.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected variable or procedure, not project

See Also

There is no variable or procedure by this name in the current scope, but there is a project by this name. This error has the following cause and solution:

The name of a project is used as a variable or procedure.

Check the spelling of the variable or procedure name, and make sure the name you want to refer to is not private to another module.  A project name can be a qualifier, but can't stand alone.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Expected: <various>

An expected part of the syntax was not found.  The error is usually located to the left of the selected item, but isn't always obvious.  For example, you can invoke a Sub procedure with or without the Call keyword.  However, if you use the Call keyword, you must enclose the argument list in parentheses.  This error has the following causes and solutions:

Expected: End of Statement [image] Improper use of parentheses in a procedure invocation:

X = Workbook.Add F:= 5	' Error due to no parentheses.

Call MySub 5	' Error due to no parentheses.

Use parentheses in a function call that specifies arguments or with a Sub procedure invocation that uses the Call keyword.

Expected: ) [image] Incorrect syntax for a procedure call. For example, a function call can't stand by itself, and Sub procedure calls sometimes require the Call keyword, depending on how you specify their arguments.

Workbook.Add (X:=5, Y:=7)	' Function call without expression.

YourSub(5, 7)	' Sub invocation without Call.

Always use function calls in expressions, and if you have multiple arguments enclosed in parentheses in a Sub procedure call, you must use the Call keyword.

Expected: Expression [image] For example, when pasting code from the Object Browser, you may have forgotten to specify a value for a named argument.

Workbook.Add (X:= )	' Error because no value assigned to

' named argument.

Either add a value for the argument, or delete it if it is optional.

Expected: Variable [image] For example, you may have used restricted keywords for variable names.  In the example below, the Input # statement expects a variable as the second argument.  Since Type is a restricted keyword, it can't be used as a variable name.

Input # 1, Type	' Type keyword invalidly used as

' variable name.

Rename the variable so it doesn't conflict with restricted keywords.

For additional information, select the item in question and press F1.


External name not defined

You can indicate external names by enclosing them in square brackets.  This error has the following cause and solution:

The identifier specified within square brackets has no meaning to the Visual Basic.

Check the spelling of the name to be sure it is consistent with that expected by the host.

For additional information, select the item in question and press F1.


File already exists (Error 58)

See Also

This error has the following causes and solutions:

At run time, this error occurs when the new filename (for example, one specified in a Name statement) is identical to a filename that already exists.

Specify a new filename in the Name statement, or delete the old file before specifying it in a Name statement.

You used the Save As command to save a currently loaded project, but the project name already exists.

Use a different project name if you don't want to replace the other project.

For additional information, select the item in question and press F1.


See Also

Kill Statement

Name Statement


File already open (Error 55)

See Also

Sometimes a file must be closed before another Open or other operation can occur.  This error has the following causes and solutions:

A sequential-output mode Open statement was executed for a file that is already open.

You must close a file opened for one type of sequential access before opening it for another.  For instance, you must close a file opened for Input before opening it for Output.

A statement (for example, Kill, SetAttr, or Name) refers to an open file.

Close the file before executing the statement.

For additional information, select the item in question and press F1.


See Also

Kill Statement

Name Statement

Open Statement

SetAttr Statement


File format no longer supported

Not all file formats are readable under all circumstances.  This error has the following cause and solution:

You are trying to load a binary file created with an earlier version of Visual Basic.

Load the file into the version of Visual Basic with which the file was created, save it in text format, then try to load it again.

For additional information, select the item in question and press F1.


File not found (Error 53)

See Also

The file was not found where specified.  This error has the following causes and solutions:

A statement (for example, Kill, Name, or Open) refers to a file that does not exist.

Check the spelling of the filename, and the path specification.

An attempt has been made to call a procedure in a dynamic-link library (DLL), but the library filename specified in the Lib clause of the Declare statement can't be found.

Check the spelling of the filename, and the path specification.

In the development environment, this error occurs if you attempt to open a project or load a text file that does not exist.

Check the spelling of the project or filename, and the path specification.

For additional information, select the item in question and press F1.


See Also

Declare Statement

Kill Statement

Name Statement

Open Statement


Fixed or static data can't be larger than 64K

Fixed and static data include nonautomatic variables, fixed-length strings, and fixed arrays.  This error has the following causes and solutions:

You attempted to allocate more than 64K of module-level data.

Reduce the amount of declared data.  Note that although the size limit for module-level data is 64K, module-level variable-length strings and arrays can exceed this limit.

You attempted to allocate more than 64K of static procedure-level data in the module.

Reduce the amount of this type of data declared.  Static data from all procedures in a module is limited to a total of 64K (not 64K per procedure).  Note that static variable-length strings and arrays can exceed this limit.

The size of a user-defined type exceeds 64K.

Reduce the size of the user-defined type.  Generally the size of a user-defined type equals the sum of the sizes specified for its elements (on some platforms there may be padding between the elements to keep them aligned on word boundaries).  Also, if you nest one user-defined type in another, the size of the nested type must be included in the size of the new type.

In a procedure, you tried to declare a variable of user-defined type that requires more than 32K.

Although the size limit of a variable of user-defined type is 64K at module level, variables of user-defined type in procedures cannot exceed 32K.  Reduce the size required for the user-defined type, or use a module-level variable.

The size of a fixed-length string declared within a procedure exceeds 65,464.

Reduce the length of the fixed-length string.  Note that variable-length strings can exceed this limit.

For additional information, select the item in question and press F1.


For control variable already in use

See Also

When you nest For...Next loops, you must use different control variables in each one.  This error has the following cause and solution:

An inner For loop uses the same counter as an enclosing For loop.

Check nested loops for repetition.  For example, if the outer loop uses For Count = 1 To 25, the inner loops can't use Count as their control variables.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

For Each...Next Statement


For Each control variable must be Variant or Object

See Also

A control variable is the element part of the For Each...Next statement syntax.  This error has the following causes and solutions:

A collection has a control variable that is not a Variant or Object type.

Make sure the element part of the For Each...Next is a Variant or Object.

An array has a control variable that is not a Variant.

Make sure the element part of the For Each...Next is a Variant.

For additional information, select the item in question and press F1.


See Also

For Each...Next Statement

Object Data Type

Variant Data Type


For Each control variable on arrays must be Variant

See Also

A control variable is the element part of the For Each...Next statement syntax.  This error has the following cause and solution:

An array has a control variable that is not a Variant.

Make sure the group part of the For Each...Next is a Variant type variable.

For additional information, select the item in question and press F1.


See Also

For Each...Next Statement

Variant Data Type


For Each may not be used on array of user-defined type or fixed-length strings

See Also

For Each constructs are only valid for collections and arrays of intrinsic types, including arrays of object.  Also, arrays of fixed-length strings cannot be iterated using For Each.  This error has the following causes and solutions:

The elements of the array in your For Each construct have a user-defined type.

Use an ordinary For...Next loop to iterate the elements of the array.

The elements of the array in your For Each construct have a fixed-length string

Use an ordinary For...Next loop to iterate the elements of the array.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

For Each...Next Statement


For Each may only iterate over a collection object or an array

See Also

The For Each construct can only be used with collections and arrays.  This error has the following cause and solution:

You specified an object that is not a collection or array as the element part of the For Each syntax.

Check the spelling of the item over which you want to iterate to make sure it corresponds to a collection or array in scope in this part of your code.

For additional information, select the item in question and press F1.


See Also

For Each...Next Statement


For loop not initialized (Error 92)

See Also

For loop counters must be initialized.  This error has the following cause and solution:

You've jumped into the middle of a For...Next loop.

Remove the jump into the loop.  Placing labels inside a For...Next loop is not recommended.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

For Each...Next Statement


For without Next

See Also

Every For statement must have a matching Next.  This error has the following cause and solution:

A For statement is used without a corresponding Next statement.

Check for an incorrectly matched For...Next structure inside the outer For...Next structure.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

For Each...Next Statement


Forward reference to user-defined type

See Also

A user-defined type must be defined before it can be referenced.  This error has the following causes and solutions:

You have declared a variable with a user-defined type before the definition of the user-defined type appears.   In the following example, the variable OtherVar is declared before its type (OtherType) is known:

Type MyType

OtherVar As OtherType

End Type

Type OtherType

WholeVar As Integer

RealVar As Double

End Type

Reposition the type definitions so that the forward reference doesn't occur.

 	You nested a user-defined type within itself.

Type MyType

MyVar As Integer

OtherVar As MyType

End Type

Remove the self-referencing nested type.  This may occur indirectly if you nest a type within another type in which the first is already declared.  Check the definition of each nested type to eliminate duplication.

For additional information, select the item in question and press F1.


See Also

Type Statement

User-Defined Data Type


Function call on left-hand side of assignment must return Variant or Object

See Also

A function call can appear on the left-hand side of an assignment, but only if the return value of the function is an Object or Variant.  This error has the following cause and solution:

The return type of the function on the left-hand side of the assignment is not a Variant or Object.

Change the return type.  Note that if the return value is an object or a Variant that contains an object, the assignment is to the default property of the object.  If the Variant returned is not an object, the assignment has no effect.

For additional information, select the item in question and press F1.


See Also

Function Statement

Object Data Type

Variant Data Type


Identifier too long

Identifiers can't be more than 255 characters long.  This error has the following cause and solution:

The identifier exceeds 255 characters.

Reduce the length of the identifier

For additional information, select the item in question and press F1.


Identifier under cursor is not a procedure name

You tried to view a procedure, but the identifier at the insertion point was not a procedure name.  This error has the following cause and solution:

Identifier is not a procedure name.

Check the spelling of the identifier.

For additional information, select the item in question and press F1.


Incorrect DLL version

Each version of Visual Basic works only with its corresponding dynamic-link library (DLL).  This error has the following cause and solution:

Your version of the Visual Basic dynamic-link library does not match the version expected.  The program is attempting to call routines in a DLL, but the version of the library is inconsistent with Visual Basic.

Obtain the correct version of the library, and make sure old versions do not precede the proper one on your path.

For additional information, select the item in question and press F1.


Incorrect OLE version

Your versions of the OLE dynamic-link libraries (DLL) do not match those expected by Visual Basic.  The application searches for the DLLs, first in the current directory, then along your path settings, and then in the WINDOWS\SYSTEM directory.  This error has the following cause and solution:

Old OLE DLLs were encountered in the search before the DLLs expected by Visual Basic.

To use both versions of the DLLs, you must place the appropriate versions in the directory from which you invoke its corresponding application.

For additional information, select the item in question and press F1.


Input past end of file (Error 62)

See Also

You cannot read past the end-of-file position.  This error has the following cause and solution:

An Input # or Line Input # statement is reading from a file in which all data has already been read or from an empty file.

Use the EOF function (immediately before the Input # statement) to detect the end of file.

For additional information, select the item in question and press F1.


See Also

EOF Function

Input # Statement

Line Input # Statement


Insufficient memory to save Undo information

You will not be able to choose the Undo command to restore the current state after you perform this edit.  This error has the following cause and solution:

The edit is too large to save for Undo.

Try performing the edit in smaller increments.

For additional information, select the item in question and press F1.


Internal error (Error 51)

See Also

Make sure this error was not generated by the Error statement or Raise method.  This error has the following cause and solution:

An internal malfunction has occurred in Visual Basic.

Unless this call was generated by the Error statement or Raise method, contact Microsoft Product Support Services to report the conditions under which the message appeared.

For additional information, select the item in question and press F1.


See Also

Error Statement

Raise Method


Invalid Access mode

See Also

In your Open statement, you specified a type of access that was invalid for the specified file type.  This error has the following causes and solutions:

You attempted to open a file for Input, but specified an illegal access mode.

You can omit the access mode specification when opening a file for input, but if you specify it, the access mode must be Read.  Both Write and ReadWrite are invalid access modes on a file opened for Input.

You attempted to open a file for Append, but specified an invalid access mode.

You can omit the access mode specification when opening a file for append, but if you specify it, the access mode must be Write.  Both Read and ReadWrite are invalid access modes on a file opened for Append

You attempted to open a file for Output, but specified an invalid access mode.

You can omit the access mode specification when opening a file for output, but if you specify it, the access mode must be Write.  Both Read and ReadWrite are invalid access modes on a file opened for Output.

For additional information, select the item in question and press F1.


See Also

Open Statement


Invalid attribute in Sub, Function, or Property

See Also

Some attributes are invalid within procedures.  This error has the following cause and solution:

A Public or Private attribute appears within the body of a procedure definition.

Remove the attribute from the procedure.  To give the variable wider scope, move the declaration to module level.  Variables declared within procedures are always Private.

For additional information, select the item in question and press F1.


See Also

Function Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Sub Statement


Invalid character

The character can't be used in the current context.  This error has the following cause and solution:

You probably used an invalid character, such as a bracket or hyphen, as part of a variable name.

Compare the spelling of the name with its declaration.

For additional information, select the item in question and press F1.


$#Invalid data format

The data read from a file was not in the expected format.  This error has the following causes and solutions:

A project file or object library file is either corrupted or in a format that can't be understood.

Get a new version of the project file or object library file.

You may have attempted to load an .EXE file into a module.

Load the source code instead.

You may have used the References dialog box and Browse dialog box from the Tools menu to add a reference to a file that is not a valid object library or contains a Basic project in a format not supported by Visual Basic

Load the questionable file into the application in which it was created, then save it in a compatible format.  For example, object library source code can be processed through MKTYPLIB and QuickBasic, and Visual Basic code can be saved in text format, and so forth.

For additional information, select the item in question and press F1.


Invalid data type for constant

Not all types of data can be assigned to constants.  This error has the following cause and solution:

You tried to declare the type of a constant to be a user-defined type, an object, or an array.

Remove the declaration or redeclare as a variable.

For additional information, select the item in question and press F1.


Invalid in Immediate pane

See Also

Not all statements are permitted in the Immediate pane.  This error has the following causes and solutions:

A declarative statement was used.  For example, Const, Declare, Deftype, Dim, Function, Option Base, Option Explicit, Option Compare, Option Private, Private, Public, property procedure declaration statements (Property Let, Property Set, and Property Get), ReDim, Static, Sub, and Type are not allowed in the Immediate pane.

Remove the declarative statements from the Immediate pane.

A control flow statement was used, for example, Sub, Function, Property, GoSub, GoTo, Return, and Resume.

Remove these statements from the Immediate pane.

There is no logical connection made between separated physical lines in the Immediate pane, so statements formatted as multiple physical lines, such as a block If statement, can't be properly executed.

Such blocks can be typed on a single physical line, with each statement separated from the next by a colon (:).  Conversely, you can extend a single statement across physical lines in the Immediate pane by using the line-continuation character, which is a space followed by an underscore ( _).

You tried to execute some code in the Immediate pane that invalidates the current state of your program and requires you to reinitialize the program.

Remove the code in question from the Immediate pane.

For additional information, select the item in question and press F1.


See Also

Const Statement

Declare Statement

Deftype Statements

Dim Statement

Function Statement

GoSub...Return Statement

GoTo Statement

If...Then...Else Statement

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

ReDim Statement

Resume Statement

Static Statement

Sub Statement

Type  Statement


Invalid inside procedure

See Also

The statement can't occur in a Sub or Function procedure. This error has the following cause and solution:

One of the following statements appears in a procedure: Declare, Deftype, Private, Public, Option Base, Option Compare, Option Explicit, Option Private, and Type.

Remove the statement from the procedure. The statements can be placed at module level.

For additional information, select the item in question and press F1.


See Also

Declare Statement

Deftype Statements

Function Statement

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement

Private Statement

Public Statement

Sub Statement

Type  Statement


Invalid length for fixed-length string

See Also

This error has the following causes and solutions:

A fixed-length string is declared with zero length.

A fixed-length string must have at least one character.

A fixed-length string exceeds the limit of 65,529 (on a 16-bit sytem) or 2^31 (on a 32-bit system).

Reduce the length specified for the fixed-length string.

Note   Variable-length strings can exceed the upper limit and can have zero length

For additional information, select the item in question and press F1.


See Also

String Data Type


Invalid or unqualified reference

See Also

An identifier beginning with a period is valid only within a With block.  This error has the following cause and solution:

The identifier begins with a period.

Complete the qualification of the identifier or remove the period.

For additional information, select the item in question and press F1.


See Also

With Statement


Invalid ordinal (Error 452)

Your call to a dynamic-link library (DLL) indicated to use a number instead of a procedure name, using the #num syntax.  This error has the following causes and solutions:

An attempt to convert the expression num to an ordinal failed.

Make sure the expression represents a valid number, or call the procedure by name.

 The num specified does not specify any function in the DLL.

Make sure num  identifies a valid function in the DLL.

A type library has an invalid declaration resulting in internal use of an invalid ordinal number.

Comment out code to isolate the procedure call causing the problem. Write a Declare statement for the procedure, and report the problem to the type library vendor.

For additional information, select the item in question and press F1.


Invalid outside procedure

See Also

The statement must occur within a Sub or Function, or a property (Property Get, Property Let, Property Set) procedure.  This error has the following cause and solution:

An executable statement, Static or ReDim, appears at module level.

Static is unnecessary at module level, since all module level variables are static.  Use Dim instead of ReDim at module level.  To create a dynamic array at module level, declare it with Dim and using empty parentheses.

Note   At module level you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type.  The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.

For additional information, select the item in question and press F1.


See Also

Const Statement

Declare Statement

Deftype Statements

Dim Statement

Function Statement

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

ReDim Statement

Static Statement

Sub Statement

Type  Statement


Invalid ParamArray use

See Also

The parameter defined as a ParamArray is being used incorrectly in the procedure.  This error has the following causes and solutions:

You attempted to pass the ParamArray as an argument to another procedure that expects an array or a ByRef Variant.

Assign the ParamArray parameter to a Variant, then pass the variant.

You attempted to use an Erase or ReDim statement with a ParamArray parameter within its procedure.

Remove the Erase or ReDim.  These operations cannot be performed on the ParamArray parameter.

For additional information, select the item in question and press F1.


See Also

ByVal Keyword

ByRef Keyword

Erase Statement

Optional Keyword

ParamArray Keyword

ReDim Statement


Invalid pattern string (Error 93)

See Also

The pattern string specified in the Like operation of a search is invalid.  This error has the following cause and solution:

A common example of an invalid character list expression is [a-b , where the right bracket is missing.

Review the valid characters for list expressions.

For additional information, select the item in question and press F1.


See Also

Like Operator


Invalid procedure call (Error 5)

See Also

Some part of the call cannot be completed.  This error has the following causes and solutions:

An argument probably exceeds the range of permitted values.  For example, the Sin function can only accept values within a certain range.  Positive arguments less than 2,147,483,648 are accepted, while 2,147,483,648 generates this error.

Check the ranges permitted for arguments.

This error may also occur if an attempt is made to call a procedure that is not valid on the current platform.

Check platform-specific information about the procedure.

For additional information, select the item in question and press F1.


See Also

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sin Function

Sub Statement


Invalid procedure name

There are restrictions in procedure naming beyond the rules for naming identifiers.  This error has the following cause and solution:

You attempted to define a procedure, but the name used for the procedure is invalid because Visual Basic already uses that identifier for another purpose.

Choose another name for the procedure.

For additional information, select the item in question and press F1.


Invalid qualifier

See Also

Qualifiers are used for disambiguation.  This error has the following cause and solution:

The qualifier does not identify a project, module, object, or a variable of user-defined type within the current scope.

Check the spelling of the qualifier.  Check to make sure that the qualifying identifier is within the current scope.  For example, a variable of user-defined type in a Private module is visible only within that module.

For additional information, select the item in question and press F1.


See Also

Private Statement


Invalid ReDim

See Also

Not every array can be redimensioned.  This error has the following causes and solutions:

A variable was implicitly declared a Variant, and you attempted to use ReDim to change it to an array.

A Variant can contain an array, but if it is not explicitly declared, you cannot use ReDim to make it into an array.  Declare the Variant before using ReDim to specify the number of elements it can contain.  For example, in the following code, ReDim AVar(10) causes an invalid ReDim error, but ReDim BVar(10) does not:

AVar = 1	' Implicit declaration of AVar.

ReDim AVar(10)	' Causes invalid ReDim error.

.

.

.

Dim BVar	' Explicit declaration of BVar.

ReDim BVar(10)	' No error.

You tried to use ReDim to change more than one dimension of an array contained within a Variant.

You can only use ReDim to change the size of the last dimension of an array in a Variant.  If you want to create an array that can have multiple dimensions that can be redimensioned, it cannot be contained within a Variant, and you have to declare it the normal way.

You can use ReDim only to change the number of elements in a normal array, not the type of those elements.

If you want an array in which you can change the types of the elements, use an array contained within a Variant.  If you declare the array first, changing the types (as well as the number) of its elements can be accomplished as follows:

Dim MyVar As Variant	' Declare the variable.

ReDim MyVar(10) As String	' ReDim it as array of String subtypes.

ReDim MyVar(20) As Integer	' ReDim it as array of Integer subtypes.

ReDim MyVar(5) As Variant	' ReDim it as array of Variant subtypes.

You attempted to use ReDim with an array that is a member of an OLE object.

Remove the ReDim.

Note   If you do not specify a type for a variable, the variable receives the default type, Variant.  This is not always obvious. For example, the following code declares two variables, the first, MyVar, is a Variant; the second, AnotherVar, is an Integer.

Dim MyVar, AnotherVar As Integer

For additional information, select the item in question and press F1.


See Also

ReDim Statement

Variant Data type


Invalid type-declaration character

See Also

Type-declaration characters are valid, but do not exist for all data types; they are not permitted in some situations.  This error has the following causes and solutions:

There is a type-declaration character appended to a variable declared in a Private, Public, or Static statement with an As clause.

Remove the type-declaration character.

A type-declaration character is appended to an inconsistent literal.  For example, since & is the type-declaration character for a Long integer, appending it to a literal of a different type causes this error:

10.253&

Remove the type-declaration character or replace it with the correct one.

For additional information, select the item in question and press F1.


See Also

Dim Statement

Private Statement

Public Statement

Static Statement


Invalid use of Null (Error 94)

See Also

Null is a Variant subtype used to indicate that a data item contains no valid data.  This error has the following cause and solution:

You are trying to obtain the value of a Variant variable or an expression that is Null.  For example:

MyVar = Null

For Count = 1 To MyVar

. . .

Next Count

Make sure the variable contains a valid value.

For additional information, select the item in question and press F1.


See Also

Variant Data Type


Invalid use of object

See Also

You tried to use an object in an incorrect way.  This error has the following causes and solutions:

You may have tried to discontinue an object reference by assigning Nothing to it, but omitted the Set keyword:

MyObject = Nothing

Use the Set statement to set an object to Nothing.  Assuming MyObject is an object, you must set it to Nothing with the Set statement:

Set MyObject = Nothing

Omitting the Set keyword is an implicit use of Let, which causes an attempt to perform a value assignment, rather than a reference assignment.  Nothing can't be used in a value assignment.

You attempted to use Nothing in an expression.

Rewrite the expression without the Nothing.

For additional information, select the item in question and press F1.


See Also

Nothing Keyword

Set Statement


Invalid watch expression

The specified watch expression is not a valid expression.  This error has the following cause and solution:

The watch expression is syntactically incorrect.

Check the syntax of all components comprising the expression.  Note that the syntax for a watch expression corresponds to the locale of the project in which the expression being watched is defined.

For additional information, select the item in question and press F1.


Label not defined

See Also

This error has the following cause and solution:

A line label or line number is referred to (in a GoTo statement, for example), but does not occur within the scope of the reference.

The label must be within the procedure that contains the reference.  Line labels are visible only in their own procedures.

For additional information, select the item in question and press F1.


See Also

GoTo Statement


Language/country setting has changed

This error has the following cause and solution:

You changed the default language/country setting for the Visual Basic environment.

Be aware that this may cause problems, though by itself it is legal.

For additional information, select the item in question and press F1.


Line too long

A physical line of Visual Basic code can contain up to 1023 characters.  This error has the following cause and solution:

A line contains too many characters.

You can create a longer logical line by joining physical lines with a line-continuation character (a space followed by an underscore ( _) character).  Up to ten physical lines can be joined with line-continuation characters to form a single logical line.  Thus, a logical line could potentially contain a total of 10,230 characters.  Beyond that, you must break the line into individual statements or assign some expressions to intermediate variables.

For additional information, select the item in question and press F1.


Loop without Do

See Also

A Do loop must begin with a Do statement.  This error has the following cause and solution:

You have an unterminated loop block nested within another loop.

Check to verify that the correct Do...Loop syntax is used.

For additional information, select the item in question and press F1.


See Also

Do...Loop Statement


LSet allowed only on strings and user-defined types

See Also

LSet is used to left align data within strings and variables of user-defined type.  This error has the following causes and solutions:

The specified variable is not a string or user-defined type.

If you are trying to block assign one array to another, LSet does not work.  You must use a loop to assign each element individually.

You tried to use LSet with an object.

LSet can also be used to assign the elements of a user-defined type variable to the elements of a different, but compatible, user-defined type.  Although objects are similar to user-defined types, you can not use LSet on them.  Similarly, you can't use LSet on variables of user-defined types that contain strings, objects, or variants.

For additional information, select the item in question and press F1.


See Also

LSet Statement

User-Defined Data Type


LSet not allowed

See Also

LSet is used to left align data within strings and variables of user-defined type.  This error has the following cause and solution:

You tried to use LSet on a user-defined type containing strings, objects, or variants.

You must assign the elements individually from this variable of user-defined type to another.

For additional information, select the item in question and press F1.


See Also

LSet Statement

RSet Statement


Maximum number of watch expressions added

There is a limit to the number of watch expressions the Watch window can contain.  This error has the following cause and solution:

You have added the maximum number of watch expressions to the Watch window.

Remove one watch expression for each new one you want to add, or display the value you want to know about in the Immediate window.

For additional information, select Add Watch from the Tools menu and press F1.


Member not defined
Method or data member not found

See Also

The collection, object, or user-defined type does not contain the referenced member.  This error has the following causes and solutions:

You may have misspelled the object or member name.

Check the spelling of the names and check the Type statement or the object documentation to determine what the members are and the proper spelling of the object or member names.

You may have specified a collection index that is out of range.

Check the Count property to determine whether a collection member exists.  Note that collection indexes begin at 1 rather than zero, so the Count property returns the highest possible index number.

For additional information, select the item in question and press F1.


See Also

Collection Object

Count Property

Type Statement


Missing end bracket

Brackets in a statement must occur in matching pairs.  This error has the following cause and solution:

An opening bracket is not matched by a closing bracket.

Place a closing bracket at the end of the material to be bracketed.

For additional information, select the item in question and press F1.


Module not found

Modules are not loaded from a code reference [image] they must be part of the project.  This error has the following cause and solution:

The requested module does not exist in the specified project.  For example, the statement MyModule.SomeVar = 5 generates this error when MyModule is not visible in the project MyProject.

To include the module in the project, choose Add File from the File menu, and then choose the module to be included from the Add File dialog box.


Must be first statement on the line

See Also

Not all keywords can appear at the beginning of a line of code.  This error has the following causes and solutions:

You have preceded a Sub, Function, or Property statement with another statement on the same line.

A Sub, Function, or Property statement must always be the first statement on any line in which it appears (unless preceded by the keyword Public, Private, or Static).

You have preceded an End If, Else, or ElseIf statement with another statement on the same line.

An End If, Else, or ElseIf (only when used in a block If structure) statement must always be the first statement on any line in which it appears.

For additional information, select the item in question and press F1.


See Also

Function Statement

If...Then...Else Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Name conflicts with existing module, project, or object library

Modules and object libraries must be uniquely named within a project.  This error has the following causes and solutions:

There is already a module or object library with this name referenced in this project.  Also, a filename extension is not considered part of the name, so different extensions can't be used to distinguish one file from another.

Use a different name for one of the duplicate module or object library references.

You attempted to add a reference to an object library whose filename (without an extension) is the same as the name of one of the project's modules.

Change either the module name or the name of the file that could not be added.

Note   Visual Basic version 4 doesn't support multiple projects.


Named argument already specified

You can use a named argument only once in the argument list of each procedure invocation.  This error has the following causes and solutions:

You specified the same named argument more than once in a single call.  For example, if the procedure MySub expects the named arguments Arg1 and Arg2, the following call would generate this error:

Call MySub(Arg1 := 3, Arg1 := 5)

Remove one of the duplicate specifications.

You specified the same argument both by positionand with a named argument, for example:

Call MySub(1, Arg1 := 3)

Remove one of the duplicate specifications.

For additional information, select the item in question and press F1.


Named arguments not allowed

Named arguments are not permitted in all situations.  This error has the following causes and solutions:

You tried to specify a named argument as an array index, for example:

MyVar = MyArray(MyNamedArg := 1)

Use an ordinary variable or constant expression as an array index.

You tried to specify a named argument with an object, for example:

MyVar = MyObject(MyNamedArg := 1)

Use a variable or constant expression if the object needs an argument.  For example, if the default for an object is a method, the object's name represents the default method.  If it needs arguments, specify them positionally.

You tried to specify a named argument with an external name:

MyVar = [MyName](MyNamedArg := 1)

Use an ordinary variable or constant expression if the external name needs an argument.

You tried to specify a named argument with a data member of an object, for example:

MyVar = [MyObject].MyProperty(MyNamedArg := 1)

Use an ordinary variable or constant expression if the data member needs an argument.

For additional information, select the item in question and press F1.


Named argument not found (Error 448)

A named argument may not be used in a procedure invocation unless it appears in the procedure definition.  This error has the following cause and solution:

You specified a named argument, but the procedure was not defined to accept an argument by that name.

Check the spelling of the argument name.

For additional information, select the item in question and press F1.


Next without For

See Also

A Next statement must have and match a preceding For statement.  This error has the following cause and solution:

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 generates this error.

For additional information, select the item in question and press F1.


See Also

For Each...Next Statement

For...Next Statement

If...Then...Else Statement


No text selected

You must select some text to perform this operation.  This error has the following cause and solution:

You did not select any text prior to initiating a Find or Replace operation.

For additional information, select the item in question and press F1.


No watch expression selected

You must have an expression selected when you choose the Instant Watch command.  This error has the following cause and solution:

You did not select an expression to watch before choosing Instant Watch.

Highlight the desired watch expression in the Code window before choosing Instant Watch.

For additional information, select the item in question and press F1.


Object doesn't support current locale setting (Error 447)

Not all objects support all locale settings.  This error has the following causes and solutions:

You attempted to access an object that does not support the locale setting for the current project.  For example, if your current project has the locale setting Canadian French, the object you are trying to access must support that locale setting.

Check which locale settings the object supports.

The object relies on national language support in a dynamic-link library (DLL), for example, OLE2NLS.DLL, that may be out of date.

Obtain a more recent version of the DLL, one that supports the current project locale.

Note   In Visual Basic, version 4.0, any object libraries used must be compatible with the English/US setting.

For additional information, select the item in question and press F1.


Object doesn't support named arguments (Error 446)

Not all objects support named arguments.  This error has the following cause and solution:

You tried to access an object whose methods do not support named arguments.

Specify arguments positionally when performing methods on this object.  See the object's documentation for more information on argument positions and types.

For additional information, select the item in question and press F1.


Object doesn't support this action (Error 445)

Not all objects support all actions.  This error has the following cause and solution:

You referenced a method or property that is not supported by this object.

See the object's documentation for more information on the object and check the spellings of properties and methods.

For additional information, select the item in question and press F1.


Object library not registered

When you start an application that uses Visual Basic, certain object libraries must be loaded.  This error has the following cause and solution:

An attempt was made to load the Visual Basic object library (VAXXX.OLB.  However, the correct language version of these object libraries could not be found in the system registry.

Any object libraries used must be compatible with the English/US setting.

Delete the VBA.INI file from your Microsoft Windows directory and restart your application.


Object library's language setting incompatible with current project

The reference couldn't be added.  This error has the following cause and solution:

You attempted to add a reference to an object library whose locale is not compatible with that of the current project..Any object libraries used must be compatible with the English/US setting.


Object not a collection (Error 451)

See Also

Certain properties, methods, and operations can only apply to Collection objects.  This error has the following cause and solution:

You specified an operation or property that is exclusive to collections, but the object is not a collection.

Check the spelling of the object or property name, or verify that the object is a Collection object.  Also, look at the Add method that was used to add the object to the collection to be sure the syntax is correct and that any identifiers were spelled correctly.

For additional information, select the item in question and press F1.


See Also

Add Method

Collection Object


Object required (Error 424)

See Also

References to properties and methods often require an explicit object qualifier.  This error has the following causes and solutions:

You referred to an object property or method, but did not provide a valid object qualifier.

Specify an object qualifier if you did not give one.  For example, although you can omit an object qualifier when referencing a form property from within the form's own module, you must explicitly specify the qualifier when referencing the property from a standard module.

You supplied an object qualifier, but it is not being recognized as an object.

Check the spelling of the object qualifier and make sure the object is visible in the part of the program in which you are referencing it.  In the case of Collection objects, check any occurrences of the Add method to be sure its syntax and spellings of all its elements is correct.

You didn't use the Set statement in assigning an object reference.  If you assign the return value of a CreateObject call to a Variant variable, an error doesn't necessarily occur if the Set statement is omitted.  Use the Set statement when assigning an object reference.

For additional information, select the item in question and press F1.


See Also

Add Method

Collection Object

Function Statement

Sub Statement


Object variable not set (Error 91)
Object variable or With block variable not set (Error 91)

See Also

There are two steps to creating an object variable.  First, you must declare the object variable; then you must assign a valid reference to the object variable, for which you use the Set statement.  Similarly, a With...End With block must be initialized by executing the With statement entry point. This error has the following causes and solutions:

You attempted to use an object variable that is not yet referencing a valid object.

Specify or respecify a reference for the object variable.  For example, if the Set statement were omitted in the following code, an error would be generated on the reference to MyObject:

Dim MyObject As Object	' Create object variable.

Set MyObject = Sheets(1)	' Create valid object reference.

MyCount = MyObject.Count	' Assign Count value to MyCount.

You attempted to use an object variable that has been set to Nothing.

Set MyObject = Nothing	' Release the object.

MyCount = MyObject.Count	' Make a reference to a released object.

Respecify a reference for the object variable.  For example, use a new Set statement to set a new reference to the object.

The object is a valid object, but it was not set because the object library in which it is described has not been selected in the Tools menu's Add References dialog box.

From the Tools menu, choose References, and select the object library in the Add References dialog box.

The target of a GoTo statement is inside a With block.  Don't jump into a With block.  Make sure the block is initialized by executing the With statement entry point.

You specified a line inside a With block when you chose the Set Next Statement command.  The With block must be initialized by executing the With statement.

For additional information, select the item in question and press F1.


See Also

Creating an Object Variable

Nothing Keyword

Set Statement


OLE Automation error (Error 440)

See Also

When you access OLE Automation objects, specific types of errors can occur.  This error has the following cause and solution:

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

Check the properties of the Err object to determine the source and nature of the error.  Also, when accessing an OLE Automation object, try using the On Error Resume Next statement immediately before the accessing statement, then check for errors immediately following the accessing statement.

For additional information, select the item in question and press F1.


See Also

Err Object

OLE Automation

On Error Statement


Object doesn't support this property or method (Error 438)

Not all objects support all properties and methods.  This error has the following cause and solution:

You specified a method or property that does not exist for this OLE automation object.

See the object's documentation for more information on the object and check the spellings of properties and methods.

For additional information, select the item in question and press F1.


Only comments may appear after End Sub, End Function, or End Property

See Also

Only comments, directives, and declarations are permitted outside procedures.  This error has the following cause and solution:

You placed executable code outside a procedure.

Any nondeclarative lines outside a procedure must begin with a comment delimiter (an apostrophe).  Declarative statements must appear before the first procedure declaration.  Comments are ignored when the code executes.

For additional information, select the item in question and press F1.


See Also

Compiler Directive Keyword Summary

End Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Optional argument must be Variant

See Also

Only Variant type variables can be optional.  This error has the following cause and solution:

You tried to specify Optional with a parameter whose data type is not Variant.

Change any optional arguments to the Variant data type.

For additional information, select the item in question and press F1.


See Also

Optional Keyword

Variant Data Type


Out of memory (Error 7)

More memory was required than is available, or a 64K segment boundary was encountered.  This error has the following causes and solutions:

You have too many applications, documents, or source files open.

Close any unnecessary applications, documents, or source files that are open.

You have a module or procedure that is too large.

Break extremely large modules or procedures into smaller ones.  This doesn't save memory, but it can prevent hitting 64K segment boundaries.

You are running Microsoft Windows in standard mode.

Restart Microsoft Windows in enhanced mode.

You are running Microsoft Windows in enhanced mode, but have run out of virtual memory.

Increase virtual memory by freeing some disk space, or at least ensure that some space is available.

You have terminate-and-stay-resident programs running.

Eliminate terminate-and-stay-resident programs.

You have many device drivers loaded.

Eliminate unnecessary device drivers.

You have run out of space for Public variables.

Reduce the number of Public variables.

For additional information, select the item in question and press F1.


Out of memory; some watches might have been deleted

When your system runs out of memory, watch expressions are deleted to make enough memory available to permit recovery from the condition.  This error has the following cause and solution:

You have too many applications or modules loaded.

To continue working, remove any dispensable elements from memory, including unnecessary applications or modules that may be loaded.

For additional information, select the item in question and press F1.


Out of resources

Certain types of resources, called "handles," are used internally for many operations.  This error has the following cause and solution:

Your code has reached a resource limit.

Try saving, closing, and reloading your code.  If you still receive this error message, reduce the number of objects referenced in the code.

For additional information, select the item in question and press F1.


Out of stack space (Error 28)

See Also

The stack is a working area of memory that grows and shrinks dynamically with the demands of your executing program.  This error has the following causes and solutions:

You have too many active Function, Sub, or Property procedure calls.

Check that procedures are not nested too deeply.  This is especially true with recursive procedures (that is, procedures that call themselves).  Make sure recursive procedures terminate properly.  Use the Calls dialog box to view which procedures are active (on the stack).

Your local variables require more local variable space than is available.

Try declaring some variables at the module level instead.  You can also declare all variables in the procedure static by preceding the Property, Sub, or Function keyword with Static.  Or you can use the Static statement to declare individual Static variables within procedures.

You have too many fixed-length strings.

Fixed-length strings in a procedure are more quickly accessed, but use more stack space than variable-length strings, because the string data itself is placed on the stack.  Try redefining some of your fixed-length strings as variable-length strings.  When you declare variable-length strings in a procedure, only the string descriptor (not the data itself) is placed on the stack.  You can also define the string at module level where it requires no stack space.  Variables declared at module level are Public by default, so the string is visible to all procedures in the module.

You have too many nested DoEvents function calls.

Use the Calls dialog box to view which procedures are active (on the stack).

Your code triggered an event cascade.

An event cascade is caused by triggering an event that calls an event procedure that is already on the stack.  An event cascade is similar to an unterminated recursive procedure call, but it is less obvious, since the call is made by Visual Basic rather than by an explicit call in your code.  Use the Calls dialog box to view which procedures are active (on the stack).

To display the Calls dialog box, select the Calls button to the right of the Procedures box in the Debug window or choose the Calls command from the Tools menu.  For additional information, select the item in question and press F1.


See Also

Creating Recursive Procedures

DoEvents Function

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Static Statement

Sub Statement


Out of string space (Error 14)

Visual Basic permits you to use very large strings.  However, the needs of other programs and the way you manipulate your strings may cause this error.  This error has the following causes and solutions:

Expressions requiring that temporary strings be created for evaluation may cause this error.  For example, the following code causes an Out of string space error on some operating systems:

MyString = "Hello"

For Count = 1 To 100

MyString = MyString & MyString

Next Count

Assign the string to a variable of another name.

Your system may have run out of memory, which has prevented a string from being allocated.

Remove any unnecessary applications from memory to create more space.


Overflow (Error 6)

An overflow results when you try to make an assignment that exceeds the limitations of the target of the assignment.  This error has the following causes and solutions:

The result of an assignment, calculation, or data type conversion is too large to be represented within the range of values allowed for that type of variable.

Assign the value to a variable of a type that can hold a larger range of values.

An assignment to a property exceeds the maximum value the property can accept.

Make sure your assignment fits the range for the property to which it is made.

For additional information, select the item in question and press F1.


ParamArray must be declared as an array of Variant

See Also

Each argument to a ParamArray parameter can be of a different data type.  Therefore, the parameter itself must be declared as an array of Variant type.  You can also supply any number of arguments to a ParamArray.  When the call is made, each argument supplied in the call becomes a corresponding element of the Variant array.  For example:

Sub MySub(ParamArray VarArg())

. . .

End Sub

Call MySub ("First arg", 2, 3.54)

This error has the following causes and solutions:

In the definition of the procedure, the ParamArray parameter is defined as an array of a type other than Variant.

Redeclare the parameter type as an array of Variant elements.

No data type was specified for the ParamArray parameter, but the procedure definition is within the scope of a Deftype statement, so the parameter is implicitly declared as having a type other than Variant.

Use an explicit As Variant clause in the specification of the ParamArray parameter.

For additional information, select the item in question and press F1.


See Also

Deftype Statements

Function Statement

ParamArray Keyword

Sub Statement

Variant Data Type


Path not found (Error 76)

See Also

The path to a file comprises the drive specification plus the directories and subdirectories that must be traversed to locate the file.  A path can be relative or absolute.  This error has the following cause and solution:

During a file- or disk-access operation (for example, Open, MkDir, ChDir, or RmDir), the operating system was unable to find the specified path.

Respecify the path.

For additional information, select the item in question and press F1.


See Also

ChDir Statement

MkDir Statement

Open Statement

RmDir Statement


Path/File access error (Error 75)

See Also

During a file- or disk-access operation (for example, Open, MkDir, ChDir, or RmDir), the operating system could not make a connection between the path and the filename.  This error has the following causes and solutions:

The file specification is not correctly formatted.

A filename can contain a fully qualified (absolute) or relative path.  A fully qualified path starts with the drive name (if the path is on another drive) and lists the explicit path from the root to the file.  Any path that is not fully qualified is relative to the current drive and directory.

You attempted to save a file that would replace an existing read-only file.

Change the read-only attribute of the target file or save the file with a different filename.

You attempted to open a read-only file in sequential Output or Append mode.

Open the file in Input mode or change the read-only attribute of the file.

For additional information, select the item in question and press F1.


See Also

ChDir Statement

MkDir Statement

Open Statement

RmDir Statement


Permission denied (Error 70)

See Also

An attempt was made to write to a write-protected disk or to access a locked file.  This error has the following causes and solutions:

You tried to open a write-protected file for sequential Output or Append.

Open the file for Input or change the write-protection attribute of the file.

You tried to open a file on a disk that is write-protected for sequential Output or Append.

Remove the write-protection device from the disk, or open the file for Input.

You tried to write to a file that another process has locked.

Wait to open the file until the other process releases it.

You attempted to access the registry, but your user permissions do not include this type of registry access.  On 32-bit Microsoft Windows systems, a user must have the correct permissions for access to the system registry.  Change your permissions or have them changed by the system administrator.

For additional information, select the item in question and press F1.


See Also

Open Statement


Procedure type mismatch
Invalid use of Property

See Also

You are using one kind of Property procedure where a different kind is expected.  This error has the following causes and solutions:

You are trying to write to a property that is read-only..

If the only property procedure defined for the property is a Property Get, you cannot assign a value to the property.  Either write an appropriate Property Let procedure, or do not attempt to write to the property..

You are trying to read a property that is write-only.

If the only property procedure defined for the property is a Property Let, you cannot read the value of the property.  Either write an appropriate Property Get procedure, or do not attempt to write to the property..

You are trying to set a reference but the property has only Property Get and/or Property Let procedures.

Either write a Property Set procedure for the property, or do not try to set a reference to it..

For additional information, select the item in question and press F1.


See Also

Property Get Statement

Property Let Statement

Property Set Statement


Project not found

The project was not found.  This error has the following cause and solution:

You specified a project name that cannot be found.

Check the way you specified the project for any errors.

For additional information, select the item in question and press F1.


Property or method not found (Error 423)

The spelling of an object name must exactly match its definition in its object library.  This error has the following cause and solution:

You referred to an object.method or object.property, but method or property is not defined.

You may have misspelled the name of the object.  To see what properties and methods are defined for an object, choose the Object Browser from the View menu.  Select the appropriate object library to view a list of available properties and methods.

For additional information, select the item in question and press F1.


Qualified name disallowed in module scope

Under some circumstances, Visual Basic doesn't permit procedure calls that include qualified names.  This error has the following cause and solution:

You specified a module name in a procedure call using dot notation (qualifier.item ).

If you are receiving this error it is probably because Visual Basic already knows the specified qualifier and doesn't need that information in the procedure call.  In such a case, you can simply omit the qualifier altogether and the procedure call will be made correctly.

For additional information, select the item in question and press F1.


Qualifier must be collection

The use of an exclamation point between two identifiers is specific to collections.  This error has the following cause and solution:

You have used a name on the left side of the exclamation point (!) that is not the name of a collection.

If the name is supposed to represent a collection, check to make sure the name is spelled correctly.  Note that the exclamation point is also the type-declaration character for the Single data type.  If the name in question is not supposed to be a collection, perhaps the ! type-declaration character appended to a variable name has been concatenated with another name.

For additional information, select the item in question and press F1.


Range has no values

There are limitations on the way you can specify the number of elements in an array.  This error has the following cause and solution:

You specified your array boundaries incorrectly.  For example, the following ranges are invalid:

Dim MyArray(10 To -5)	' Descending order not permitted.

Dim MyArray(0 To 0)	' No elements in the array.

Check to be sure your syntax is correct.  For example, the following range is valid:

Dim MyArray(-5 To 10)

For additional information, select the item in question and press F1.


Resume without error (Error 20)

See Also

A Resume statement may only appear within an error handler and can only be executed in an active error handler.  This error has the following causes and solutions:

You placed a Resume statement outside error-handling code.

Move the statement into an error handler, or delete it.

Your code jumped into an error handler even though there was no error.

Perhaps you misspelled a line label.  Jumps to labels cannot occur across procedures, so search the procedure for the label that identifies the error handler.  If you find a duplicate label specified as the target of a GoTo statement that is not an On Error GoTo statement, change the line label to agree with its intended target.

For additional information, select the item in question and press F1.


See Also

GoTo Statement

On Error Statement

Resume Statement


Return without GoSub (Error 3)

See Also

A Return statement must have a corresponding GoSub statement.  This error has the following cause and solution:

You have a Return statement that cannot be matched with a GoSub statement.

Make sure your GoSub statement was not unintentionally deleted.

Unlike For...Next, While...Wend, and Sub...End Sub, which are matched at compile time, GoSub and Return are matched at run time.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

GoSub...Return Statement

Sub Statement

While...Wend Statement


RSet allowed only on strings

See Also

RSet is used to right align string data within fixed-length or variable-length strings.  This error has the following cause and solution:

You tried to use the RSet statement on a variable that is not a string.

If appropriate, try converting the variable to a string.  Otherwise, don't use RSet.

Note   Although the LSet statement can be used to assign the elements of one user-defined type variable to the elements of a different, but compatible, user-defined type, such assignments are discouraged because they cannot be guaranteed to be portable.

For additional information, select the item in question and press F1.


See Also

LSet Statement

RSet Statement


Run-time error <number>:

This error is user-defined, and has the following cause and solution:

An error was generated that does not correspond to a Visual Basic error.

Handle the error as indicated in the documentation for the object or object library that generated the error.

For additional information, select the item in question and press F1.


Search string too long or complex

See Also

Visual Basic pattern-matching capabilities are not unlimited.  This error has the following cause and solution:

The search string specified is either too long, or the combination of wildcard character specifications can't be understood.

Reduce the length or complexity of the search string and retry the search.

For additional information, select the item in question and press F1.


See Also

Like Operator


Search string must be specified

See Also

You have to specify a search string.  This error has the following cause and solution:

You tried to perform a search operation without a string for comparison.

You must specify the search string.  While you can specify a zero-length string ("") as a replacement string, a zero-length string has no meaning as a search string.

For additional information, select the item in question and press F1.


See Also

Comparison Operators

Like Operator


Search text is not found

See Also

No search text was found.  This error has the following causes and solutions:

There is no matching text between the start point and end point of the specified search scope.

You can widen the scope of the search if you want to continue searching.

You failed to provide a left bracket when using a pattern-matching expression.

Provide the left bracket.

For additional information, select the item in question and press F1.


See Also

Like Operator


Seek failed: can't read/write from the disk

See Also

Seek statements are carried out directly to disk.  This error has the following causes and solutions:

You attempted to read from a disk or file that is write-protected, read-only, or locked.

Remove the write-protected attribute or change the read-only attribute or lock.  Note that if the file is locked by another process, you cannot remove the lock.

The file has become unavailable (for example, if a removable disk has been physically changed).

If the file has been moved to another disk, access it from there.  Otherwise, you cannot access the file.

You attempted to read from a project file, an object library, or a type library, but the file has been corrupted.

Obtain a new copy of the library or project file.

For additional information, select the item in question and press F1.


See Also

Seek Statement


Select Case without End Select

See Also

Each Select Case construct must be terminated with an End Select statement.  This error has the following cause and solution:

You used a Select Case statement without a corresponding End Select statement.

Check if there is an incorrectly matched Select Case...End Select structure inside an outer Select Case...End Select structure.  If you have nested Select Case statements, each must have a matching End Select.

For additional information, select the item in question and press F1.


See Also

End Statement

Select Case Statement


Selected watch expression invalid

See Also

It is not always possible to select a valid watch expression.  This error has the following causes and solutions:

You chose the Instant Watch command, but the selected expression is not a valid expression.  For example, you can't watch a comment or a Sub procedure call.

Select the expression in such a way that it is valid, or choose Add Watch from the Tools menu and type in a valid expression.

The watch expression must have code syntax corresponding to the locale of the project that defines the expression being watched.

Rewrite the expression in a way that is valid for the locale.

For additional information, select the item in question and press F1.


See Also

Sub Statement


SHARE.EXE required

The program SHARE.EXE must be running when you start Visual Basic.  This error has the following cause and solution:

You didn't start SHARE.EXE before starting Visual Basic.

Close your application, start SHARE.EXE, then restart your application.  To avoid this problem in the future, place an invocation of SHARE.EXE in your AUTOEXEC.BAT file so SHARE.EXE automatically starts when you turn on your machine.

For additional information, select the item in question and press F1.


Specified DLL function not found (Error 453)

The dynamic-link library (DLL) in a user library reference was found, but the DLL function specified was not found within the DLL.  This error has the following causes and solutions:

You specified an invalid ordinal in the function declaration.

Check for the proper ordinal, or call the function by name.

You gave the right DLL name, but it is not the version that contains the specified function.

You may have the proper version on your machine, but if the directory containing the wrong version precedes the directory containing the proper one in your path, the wrong DLL is accessed.  Check your machine for different versions.  If you have an old version, contact the supplier for a newer version.

If you are working on a 32-bit Microsoft Windows platform, both the DLL name and alias (if used) must be correct.

Make sure the DLL name and alias are correct.

Some 32-bit DLLs contain functions with slightly different versions to accommodate both Unicode and ANSI strings.  An A at the end of the function name specifies the ANSI version.  A W at the end of the function name specifies the Unicode version.

If the function takes string-type arguments, try appending an A to the function name.

For additional information, select the item in question and press F1.


Specified library or project already referenced

The Add References dialog box displays referenced libraries.  This error has the following cause and solution:

You chose the Browse button in the Add References dialog box, then selected a type library that was already listed in the Available References section of the Add References dialog box.

If you want to make a project or type library part of your project, choose References from the Tools menu and make sure the type library is checked.

Note   Visual Basic version 4 doesn't support multiple projects.

For additional information, select the item in question and press F1.


Statement invalid inside Type block

See Also

Only element names (and their As type clauses) and comments are allowed within a Type...End Type statement block.  This error has the following cause and solution:

You placed an invalid statement in a user-defined type definition.

Remove anything that is not a comment, an element name, or an As type clause.

For additional information, select the item in question and press F1.


See Also

Type Statement


Statement invalid outside Type block

See Also

The syntax for declaring variables outside a Type...End Type statement block is different from the syntax for declaring the elements of the user-defined type.  This error has the following causes and solutions:

You tried to declare a variable outside a Type...End Type block or outside a statement.

When declaring a variable with an As clause outside a Type...End Type block, use one of the declaration statements, Dim, ReDim, Static, Public, or Private.  For example, the first declaration of MyVar in the following code generates this error; the second and third declarations of MyVar are valid:

MyVar As Double	' Invalid declaration syntax.

Dim MyVar As Double

Type AType

MyVar As Double	' This is valid declaration syntax

End Type	' because it's inside a Type block.

You used an End Type statement without a corresponding Type statement.

Check for an unmatched End Type, and either precede its block with a Type statement, or delete it if it isn't needed.

For additional information, select the item in question and press F1.


See Also

Type Statement


Statement too complex

See Also

Visual Basic is unable to analyze this statement.  This error has the following causes and solutions:

Your statement cannot be parsed due to its complexity.

Try breaking the statement into several smaller components or replace complex conditional clauses with a combination of logical operators and If...Then...Else statements.

Your statement or function uses too many nested function calls.

Make function calls earlier and assign the results to specific variables; then use the variables in the statement that is causing the complexity error.

For additional information, select the item in question and press F1.


See Also

If...Then...Else Statement


Statements or labels invalid between Select Case and first Case

See Also

You can place nothing but a comment between the Select Case statement and the first Case clause.  This error has the following cause and solution:

You placed a statement between Select Case and its first Case clause.  For example:

Select Case SomeVar

' This is a comment and is valid.

Stop	' Even a Stop statement is invalid here.

Case SomeValue

. . .

End Select

The Select Case statement must be immediately followed by its first Case statement.  If the intervening expression is a comment, precede it with a comment delimiter (').  Otherwise, place the expression where it belongs, or delete it.

For additional information, select the item in question and press F1.


See Also

Select Case Statement


String expression too complex (Error 16)
Expression too complex (Error 16)

The number of subexpressions allowed in a floating-point expression varies among platforms. For example, on 32-bit Microsoft Windows operating systems the limit is eight levels of nested floating-point expressions  This error has the following cause and solution:

A floating-point expression contains too many nested subexpressions.  Break the expression into as many separate expressions as necessary to prevent the error from occurring.

Note   In earlier versions of Visual Basic, Error 16 was "String expression too complex." That error condition can no longer occur.  However, if you have old code that traps and handles that error, you should remove it to prevent confusion with this new error.

For additional information, select the item in question and press F1.


Sub, Function, or Property not defined (Error 35)

See Also

A Sub, Function, or Property procedure must be defined to be called.  This error has the following causes and solutions:

You misspelled the name of your procedure.

Check the spelling and correct it.

You tried to call a procedure from another project without explicitly adding a reference to that project in the Add References dialog box of the Tools menu.

To add a reference:

1	Choose References from the Tools menu.

2	Find the name of the project containing the procedure you want to call.  If the project name doesn't appear in the dialog box, click the Browse button to search for it.

3	Select the check box to the left of the project name.

4	Click OK.

The specified procedure is not visible to the calling procedure.

Procedures declared Private in one module can't be called from procedures outside the module.  If Option Private Module is in effect, procedures in the module are not available to other projects.  Choose Find from the Edit menu to locate the procedure.

You declared a dynamic-link library (DLL) routine, but the routine is not in the specified library.

Check the ordinal (if you used one) or the name of the routine.  Make sure your version of the DLL is the correct one.  The routine may only exist in newer versions of the DLL.  If an older version appears in a directory that precedes the directory the newer one is in, an error occurs because Visual Basic accesses the version in the first directory that appears on your path.

Note   Visual Basic version 4 doesn't support multiple projects.

For additional information, select the item in question and press F1.


See Also

Function Statement

Option Private Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Subscript out of range (Error 9)

See Also

Elements of arrays and members of collections can only be accessed within their defined ranges.  This error has the following causes and solutions:

You referenced a nonexistent array element.

The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application.  Check the declaration of the array to be sure of its upper and lower bounds.  Use the UBound and LBound functions to condition array accesses if you are working with arrays that are redimensioned.  If the index is specified as a variable, check the spelling of the variable name.

You declared an array but didn't specify its number of elements.  For example, the following code causes this error:

Dim MyArray() As Integer

MyArray(8) = 234	' Causes Error 9.

Visual Basic does not implicitly dimension unspecified array ranges as 0 [image] 10.  Instead, you must use Dim or ReDim to specify explicitly the number of elements in an array.

You referenced a nonexistent collection member.

Try using the For Each...Next construct instead of specifying index elements.

For additional information, select the item in question and press F1.


See Also

Creating Arrays

Dim Statement

For Each...Next Statement

LBound Function

ReDim Statement

UBound Function


Syntax error

See Also

Visual Basic can't determine what action to take.  This error has the following causes and solutions:

A keyword or argument is misspelled.

Keywords and the names of named arguments must exactly match those specified in their syntax specifications.  Check online Help, then correct the spelling.

Punctuation is incorrect.

For example, when you omit optional arguments positionally, you must substitute a comma (,) as a placeholder for the omitted argument.

A procedure is not defined.

Check the spelling of the procedure name.

You tried to specify both Optional and ParamArray in the same procedure declaration.

A ParamArray argument cannot be Optional.  Choose one and delete the other.

For additional information, select the item in question and press F1.


See Also

Optional Keyword

ParamArray Keyword

Sub Statement


Too many arguments

See Also

A procedure can have only 60 arguments.  This error has the following cause and solution:

You specified more than 60 arguments.

If you must specify more arguments, define a user-defined type to collect multiple arguments of different types, or use a ParamArray as the final argument and pass multiple values to it.  You can also pass multiple arguments by placing them in an array.

For additional information, select the item in question and press F1.


See Also

ParamArray Keyword


Too many dimensions

See Also

Arrays can have no more than 60 dimensions.  This error has the following causes and solutions:

You tried to declare an array with more than 60 dimensions.

Reduce the number of dimensions.

Your array declaration is within the specified limits, but there is not enough memory to actually create the array.

Either make more memory available, or reduce the number of dimensions.  Also, if your array is an array of Variant type or an array contained within a Variant, you may be able to create the array with the same number of dimensions by redeclaring it with the data type of its elements.  For example, if it contains only integers, declaring it as an array of Integer type uses less memory than if each element is a Variant.

For additional information, select the item in question and press F1.


 See Also

Creating Arrays

ReDim Statement


Too many DLL application clients
Too many DLL application clients (Error 47)

The dynamic-link library (DLL) for Visual Basic can only accommodate access by 50 host applications at a time.  This error has the following cause and solution:

Your application, and other applications that are Visual Basic hosts (some of which may be accessed by your application), are all attempting to access the Visual Basic DLL at the same time.

Reduce the number of open applications accessing Visual Basic.

For additional information, select the item in question and press F1.


Too many files (Error 67)

There is a limit to the number of disk files that can be open at one time.  This error has the following causes and solutions:

MS-DOS operating system [image] more files have been created in the root directory than the operating system permits.

The MS-DOS operating system limits the number of files that can be in the root directory (usually 512).  If your program is opening, closing, or saving files in the root directory, change your program so that it uses a subdirectory.

MS-DOS operating system [image] more files have been opened than the number specified in the files= setting in your CONFIG.SYS file.

Increase the number specified in the files= setting in your CONFIG.SYS file and restart your computer.

For additional information, select the item in question and press F1.


Too many line continuations

There is a limit to the number of lines you can join with line-continuation characters.  This error has the following cause and solution:

Your code has more than 10 consecutive lines joined with line-continuation characters.

Make some of the constituent lines physically longer (to reduce the number of line-continuation characters needed), or break the construct into more than one statement.

For additional information, select the item in question and press F1.


Type-declaration character does not match declared data type

The data type of a variable cannot be changed by appending the type-declaration character for another type.  This error has the following cause and solution:

You declared a variable of a specific type, then referenced a variable of the same name in the same scope and appended an inconsistent type-declaration character.

If you want to be able to change the type of data assigned to a variable, declare the variable as a Variant.  If you simply appended an incorrect type-declaration character, delete or change it.

For additional information, select the item in question and press F1.


Type-declaration character not allowed

See Also

While using type-declaration characters is valid in Visual Basic, some recently added data types (including Byte, Boolean, Date, Object, and Variant) have no associated type-declaration characters.  This error has the following causes and solutions:

You tried to use a type-declaration character in the declaration of a variable that uses the As clause, as for instance with Dim, Static, Public, and so on.

Either remove the type-declaration character or remove the As clause.

You tried to use a type-declaration character in reference to a variable that was implicitly declared without a type-declaration character:

MyVar = 20	' Implicit declaration.

MyVar% = 25	' Generates an error.

Either remove the type-declaration character or redeclare the original variable.

Note   If an explicit variable declaration contains a type-declaration character, inclusion of the character is optional in later references.  For example:

Dim MyStr$

MyStr = "Because it was explicitly declared, the $ is optional."

For additional information, select the item in question and press F1.


See Also

Data Type Summary

Dim Statement

Public Statement

Static Statement

Variant Data Type


Type-declaration character required

The necessity of using type-declaration characters depends on the form of the identifier's declaration.  This error has the following cause and solution:

A variable that was originally implicitly declared with a type-declaration characters was referenced without a type-declaration character.  For example:

MyStr$ = "Implicit declaration"

MyStr = "Trying to refer to MyStr$, but error results" _

 & "from calling it MyStr."

Either make the declaration explicit, or add the type-declaration character to later references.

Note   If an explicit variable declaration contains a type-declaration character, inclusion of the character is optional in later references.  For example:

Dim MyStr$

MyStr = "Because it was explicitly declared, the $ is optional."

For additional information, select the item in question and press F1.


Type mismatch (Error 13)

See Also

Visual Basic version 4.0 is able to convert and coerce many values to accomplish data type assignments that were not possible in previous versions.  However, this error can still occur and has the following causes and solutions:

The variable or property is not of the correct type.  For example, a variable that requires an integer value can't accept a string value unless the whole string can be recognized as an integer.

Try to make assignments only between compatible data types.  For example, an Integer can always be assigned to a Long, a Single can always be assigned to a Double, and any type (except a user-defined type) can be assigned to a Variant.

An object was passed to a procedure that is expecting a single property or value.

Pass the appropriate single property, or call a method appropriate to the object.

A module or project name was used where an expression was expected, for example:

Debug.Print MyModule

Specify an expression that can be displayed.

You attempted to mix traditional Basic error handling with Variant values having the Error subtype (10, vbError); for example:

Error CVErr(n)

If you need to regenerate an error, you must map it to an intrinsic Visual Basic (or a user-defined) error, then generate that error.

A CVErr value can't be converted to Date for example:

MyVar = CDate(CVErr(9))

Use a Select Case statement, or some similar construct, to map the return of CVErr to such a value.

At run time, this error typically indicates that a Variant used in an expression has an incorrect subtype, or a Variant containing an array appears in a Print # statement.

To print arrays, create a loop that displays each element individually.

For additional information, select the item in question and press F1.


See Also

CVErr Function

Data Type Summary

Print # Statement

Select Case Statement


Type mismatch: array or user-defined type expected

See Also

The type of an argument or parameter includes whether or not it is an array or a user-defined type.  This error has the following cause and solution:

Your argument specified a single element of an array or user-defined type, or a simple variable, literal, or constant.  However, it is being passed to a parameter that expects a whole array or user-defined type.

Either change the argument or change the definition of the parameter.

Your argument specified an array or user-defined type, but it was not of the same type as the parameter.

Either pass an array of the expected type or change the definition of the parameter declaration.

For additional information, select the item in question and press F1.


See Also

Type Statement


Unable to read from the disk

There is a general problem reading from a disk.  This error has the following causes and solutions:

The disk drive door is improperly closed.

If the disk is removable, check the drive door.  Close it properly if necessary.

The disk may be inserted upside down.

Reinsert the disk right-side up.

The disk may not be properly formatted.

Reformat the disk if you are willing to lose the data it currently contains.

You are experiencing network problems.

Try restarting your network.

You placed a disk of a certain density in a drive that cannot read it.

Use a different drive, or copy the material you want to a disk that can be read on your drive.

For additional information, select the item in question and press F1.


Unable to write to the disk

There is a general problem writing to a disk.  This error has the following causes and solutions:

The disk drive door is improperly closed.

If the disk is removable, check the drive door.  Close it properly if necessary.

The disk may be inserted upside down.

Reinsert the disk right-side up.

The disk may not be properly formatted.

Reformat the disk if you are willing to lose the data it currently contains.

You are experiencing network problems.

Try restarting your network.

You placed a disk of a certain density in a drive that cannot write to it.

Use a different drive, or copy the material you want to a disk that can be read on your drive.

For additional information, select the item in question and press F1.


Unmatched brackets in search string

An opening bracket must be matched by a closing bracket.  This error has the following cause and solution:

You opened a bracket pair in a search string, but did not close it with a matching closing bracket.

Place a closing bracket in the appropriate place.

For additional information, select the item in question and press F1.


Unrecognized project language

The specified code locale for the project to be loaded is not currently supported by this application.  This error has the following causes and solutions:

The project was created on a system that supports the code locale, but was then moved to a system where that code locale is not recognized.  For example, the OLE2NLS.DLL on the current machine may be a version that does not recognize the code locale.

Install the proper dynamic-link library (DLL) on the current system.

The correct object library for the project was not found.

Make sure the correct object libraries are available, for example, make sure your path includes their directories.

For additional information, select the item in question and press F1.


Object library feature not supported

It is possible to have features in an object library that have no equivalent in Visual Basic.  This error has the following cause and solution:

An attempt was made to access an object library data type or function that can't be supported by Visual Basic.

Contact the creator of the object library for more information on when it is appropriate to use the object library, and the tools with which it should be used.

For additional information, select the item in question and press F1.


User interrupt occurred (Error 18)

The process of breaking execution is useful, but if left unhandled, results in termination of the application.  This error has the following cause and solution:

A user pressed CTRL+BREAK or another interrupt key.

In the development environment, continue execution.  To provide for the occurrence of this condition at run time, handle the error in an appropriate way.

For additional information, select the item in question and press F1.


Application-defined or object-defined error

See Also

This message is displayed when an error is generated with the Raise method or Error statement that does not correspond to an error defined by Visual Basic for applications.  It is also returned by the Error function for arguments that don't correspond to errors defined by Visual Basic for applications.  Thus it may be an error you have defined, or one that is defined by an object.  For example, Visual Basic forms generate many form-related errors that cannot be generated from code simply by specifying a number as an argument to the Raise method or Error statement.  This message has the following causes and solutions:

Your application executed an Err.Raise n or Error n statement, but the number n is not defined by Visual Basic for applications.

If this was what was intended, you have to use Err.Raise and specify additional arguments if you want an end user to understand the nature of the error.  For example, you can include a description string, source, and help information.  If you are trying to regenerate an error that you trapped, this approach will work if you do not execute Err.Clear before regenerating the error.  If you execute Err.Clear first, you must fill in the additional arguments to the Raise method.  Look at the context in which the error occurred, and make sure you are regenerating the same error.

It may be that in accessing objects from other applications, an error was propagated back to your program that could not be mapped to a Visual Basic error.

Check the documentation of any objects you have accessed.  The Err object's Source property should contain the programmatic ID of the application or object that generated the error.  To more accurately understand the context of an error returned by an object, you may want to use the On Error Resume Next construct in code that accesses objects, rather than the On Error GoTo line syntax.

Note   In the past programmers have often used a loop to print out a list of all trappable error message strings.  Typically this was done with code such as the following:

For index = 1 to 500

Debug.Print Error$(index)

Next index

Such code still lists all the Visual Basic for applications error messages, but displays "Application-defined or object-defined error," for example those that relate to forms, controls, and so on.  Many of these are trappable runtime errors. You can use Help's Search dialog to find the list of trappable errors. Press the Search button and type Trappable in the first text box, then press the Show Topics. Select Trappable Errors in the lower list box and press the Go To button.

For additional information, select the item in question and press F1.


See Also

Clear Method

Err Object

Error Function

Error Statement

On Error Statement

Raise Method

Source Property


User-defined type may not be passed ByVal

See Also

User-defined types can only be passed by reference (the default), not by value.  The error may not be reported until the call is made.  This error has the following cause and solution:

You placed a ByVal keyword in the definition of a parameter that represented a user-defined type.

Remove the ByVal keyword.  If you want to keep changes from being propagated back to the caller, Dim a temporary variable of the type and pass the temporary variable into the procedure.

For additional information, select the item in question and press F1.


See Also

ByVal Keyword

Dim Statement

Type Statement


User-defined type not defined

See Also

You can create your own data types in Visual Basic, but they must be defined first in a Type...End Type statement or in a properly registered object library or type library.  This error has the following causes and solutions:

You tried to declare a variable or argument with an undefined data type or you specified an unknown class or object name.

Use the Type statement in a module to define a new data type.  If you are trying to create a reference to a class, the class must be visible to the project.  If you are referring to a class in your program, you must have a class module of the specified name in your project.  Check the spelling of the type name or name of the object.

The type you want to declare is in another module, but has been declared Private.

Move the definition of the type to a standard module where it can be Public.

The type is a valid type, but the object library or type library in which it is defined is not registered in Visual Basic.

Choose References from the Tools menu, then select the appropriate object library or type library in the Add References dialog box.  For example, if you don't check the Data Access Object in the Add References dialog box, types like Database, Recordset, and TableDef are not recognized and references to them in code causes this error.

For additional information, select the item in question and press F1.


See Also

As Keyword

Private Keyword

Type Statement


User-defined type without members not allowed

See Also

User-defined types must have at least one element.  This error has the following cause and solution:

You specified an empty user-defined type in a Type...End Type definition.

Check the Type statement for unintended comment delimiters.

For additional information, select the item in question and press F1.


See Also

Type Statement


Variable not defined

See Also

You use the Option Explicit statement to protect your modules from having undeclared variables and to eliminate the possibility of inadvertently creating new variables when typographical errors occur.  This error has the following cause and solution:

You used an Option Explicit statement to require the explicit declaration of variables, but you used a variable without declaring it.

Explicitly declare the variable, or change the spelling of the variable to match that of the intended variable.

For additional information, select the item in question and press F1.


See Also

Option Explicit Statement


Variable required

See Also

This error typically occurs when you attempt to assign a value to something that can't accept the assignment.  This error has the following causes and solutions:

You attempted to use a numeric expression as an argument to the Len function.

The Len function does not accept a numeric expression, a numeric literal, or a binary numeric expression, but it does accept either a string or numeric variable, a string expression, or a variable of user-defined type.

You used a function call or an expression as an argument to Input #, Let, Get, or Put.  For example, you 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.

Input #, Let, Get, and Put do not accept function calls as arguments.

You attempted to assign a value to an identifier previously declared as a constant.

Choose another name for the identifier.

You tried to use a nonvariable as a loop counter in a For...Next construction.

Use a variable as the counter.

You tried to assign a value to a read-only property or to an expression that consists of more than one variable (such as X + Y).  An assignment places a value at a memory location.  The specified expression must represent a single, writable location.  Rewrite the assignment to a single variable name that can accept the data.

You tried to use an undeclared variable that is defined as a constant in a type library.  Either use a different name for the variable, or declare it explicitly.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

For Each...Next Statement

Get Statement

Input # Statement

Len Function

Let Statement

Put Statement


Object library for Visual Basic for applications not found

The Visual Basic object library (VAXXX.OLB or VAXXXX.OLB) corresponding to the language of the project could not be found.  This error has the following causes and solutions:

The object library either is missing completely, is not in the expected directory, or is an incorrect version.

Search your disk to make sure the object library is in the correct directory.

Note   In Visual Basic, version 4.0, any object libraries used must be compatible with the English/US setting.

If you cannot find a missing object library on your system, contact the author.  If the missing library is a Microsoft application object library, you can obtain it as follows:

If you have access to Microsoft electronic technical support services, refer to the technical support section of this Help file.  Under electronic services, you will find instructions on how to use the appropriate service option.

If you do not have access to Microsoft electronic technical support services, Microsoft object libraries are available upon request as an application note from Microsoft.  Information on how to contact your local Microsoft product support organization is also available in the technical support section of this Help file.

For additional information, select the item in question and press F1.


Warning: custom language settings not portable

Not all language settings are portable.  This warning has the following cause and solution:

You used a custom language setting in your code.

When you choose a Custom language/country setting for your code, the language conventions used in your code match those set in the Control Panel of your system.  You can use custom code locale settings, but your code may not work in other locales or on other systems with different settings.  The host application parses some strings based on the Control Panel settings of the machine on which it is running.

If the Control Panel settings on the target machine are not the same as those on the machine on which the code was written, strings parsed by a host application (for example, code that depends on a locale-specific decimal separator) don't work.  Therefore, you should not use a Custom language setting unless you do not intend to send your code to other users.  If you plan to send your code to other users, select a predefined locale.

Note   In Visual Basic, version 4.0, any object libraries used must be compatible with the English/US setting.

For additional information, select the item in question and press F1.


Wend without While

See Also

Every Wend statement must be preceded by a matching While statement.  This error has the following cause and solution:

You used a Wend statement without a preceding While statement.

Check for an unterminated loop nested within the While...Wend loop that is causing the error.

For additional information, select the item in question and press F1.


See Also

While...Wend Statement


While without Wend

See Also

A While statement is used without a corresponding Wend statement.  This error has the following cause and solution:

You opened a While...Wend construct, but did not close it.

Check for an incorrectly matched While...Wend structure inside the outer While...Wend structure.

For additional information, select the item in question and press F1.


See Also

While...Wend Statement


Wrong number of arguments (Error 450)

See Also

The number of arguments to a procedure must match the number of parameters in the procedure's definition.  This error has the following causes and solutions:

The number of arguments in the call to the procedure was not the same as the number of required arguments expected by the procedure.

Check the argument list in the call against the procedure declaration or definition.

You specified an index for a control that is not part of a control array.  The index specification is interpreted as an argument, but because neither an index nor an argument is expected, the error occurs.  Remove the index specification, or follow the procedure for creating a control array (that is, set the Index property to a nonzero value in the control's property sheet or property window at design time).

You specified an index for a control that is not part of a control array.  The index specification is interpreted as an argument, but because neither an index nor an argument is expected, the error occurs.  Remove the index specification, or follow the procedure for creating a control array (that is, set the Index property to a nonzero value in the control's property sheet or property window at design timedefdesigntime).

You tried to assign a value to a read-only property, or you tried to assign a value to a property for which no Property Let procedure exists.

Assigning a value to a property is the same as passing the value as an argument to the object's Property Let procedure.  Properly define the Property Let procedure (it must have one more argument than the corresponding Property Get procedure).  If the property is meant to be read-only, you can't assign a value to it.

For additional information, select the item in question and press F1.


See Also

Function Statement

Sub Statement


Wrong number of dimensions

See Also

You must reference an array with indexes corresponding to the same number of dimensions as appear in the array's declaration.  This error has the following cause and solution:

You referred to an array with a different number of dimensions than it actually contains.  For example, referring to an array as X(2,4) (an array with two dimensions), when it has been defined as Dim X(5) (an array with one), generates this error.

Check the declaration of the array and, in the reference, include one index for each dimension in the declaration.

For additional information, select the item in question and press F1.


See Also

Creating Arrays

Dim Statement


You'll have to restart your program after this edit [image] proceed anyway?

You can edit code in break mode, but some edits prevent continuing execution.  This error has the following cause and solution:

You attempted an edit that prevents continued execution, for example, you declared a static variable.

If you choose Yes, execution will terminate and you can edit your code.  If you choose No, you can continue running the code from the point at which it was suspended.

For additional information, select the item in question and press F1.


With object must be user-defined type, Object, or Variant

See Also

The With...End With block cannot be used with all variable types.  This error has the following cause and solution:

You tried to use a variable that was not of Object type, user-defined type, or Variant type containing an object within a With block.

Check to see if you misspelled the name of the object, user-defined type, or Variant variable.

For additional information, select the item in question and press F1.


See Also

Object Data Type

With Statement


Line is not an executable statement

Declarations and comments are not executable statements.  This error has the following cause and solution:

You chose the Step To Cursor command from the Run menu, but the cursor was not on a line containing an executable statement.

Place the cursor on an executable statement near the current line.

For additional information, select the Step To Cursor command from the Run menu and press F1.


Set Next Statement can only apply to executable lines within current procedure.

You can choose the Set Next Statement command from the Run menu to indicate where a suspended program should begin when execution is continued.  This error has the following causes and solutions:

When you chose the command, the cursor was on a line that did not contain an executable statement.

Place the cursor on a line with an executable statement and try again.  Declarations, line labels, and comments are not executable, so lines with only declarations, labels, and comments cannot be the targets of the Set Next Statement command.

When you chose the command, the cursor was on a line outside the currently executing procedure.

Place the cursor on a line within the currently executing procedure.


Can't execute immediate statements in design mode

Design time is any time that your code is not being executed, or is suspended and waiting to be continued.  This error has the following cause and solution:

You tried to execute a statement in the Immediate window, but you have not yet chosen the Start command from the Run menu.

Choose Start from the Run menu, and then suspend program execution.  You can then execute code in the Immediate window.

For additional information, place the cursor in the Immediate window and press F1.


Invalid use of Me keyword

See Also

The Me keyword can appear in form modules and class modules.  This error has the following causes and solutions:

The Me keyword appeared in a standard module.

The Me keyword cannot appear in a standard module since a standard module does not represent an object.  If you copied the code in question from a class module or form module , you have to replace the Me keyword with the specific object or form name in order to preserve the original reference.

The Me keyword appeared on the left-hand side of a Set assignment, for example:

Set Me = MyObject	' Causes "Invalid use of Me keyword" message.

Remove the Set assignment.

Note   The Me keyword can appear on the left-hand side of a Let assignment, in which case the default property of the object represented by Me is set.  For example:

Let Me = MyObject	' Valid assignment with explicit Let.

Me = MyObject	' Valid assignment with implicit Let.

For additional information, select the item in question and press F1.


 See Also

Let Statement

Me Keyword

Set Statement


Invalid use of New keyword

See Also

The New keyword can only be applied to an OLE creatable object (and instance of a class or OLE Automation object).  This error has the following causes and solutions:

You tried to instantiate something that can have only one instance.  For instance, you tried to create a new instance of a module by specifying Module1 in a statement like the following:

Dim MyMod As New Module1

You can't create the new instance, since a module can have only one instance.

You tried to instantiate an OLE object, but it was not an OLE creatable object.  For instance, you tried to create a new instance of a list box by specifying ListBox in a statement like the following:

' Valid syntax to create the variable.

Dim MyListBox As ListBox

Dim MyFormInst As Form

' Invalid syntax to instantiate the object.

Set MyFormInst = New Form

Set MyListBox = New ListBox

ListBox and Form are class names, not specific object names.  You can use them to specify that a variable will be a reference to a certain object type, as with the valid Dim statements above.  But you can't use them to instantiate the objects themselves in a Set statement.  You must specify a specific object, rather than the generic class name, in the Set statement:

' Valid syntax to create new instance of a form or list box.

Set MyFormInst = New Form1

Set MyListBox = New List1

For additional information, select the item in question and press F1.


 See Also

Dim Statement

New Keyword

Set Statement


Constants, fixed-length strings, and arrays not allowed as Public members of class module
Constants, fixed-length strings, arrays, and Declare statements not allowed as Public members of class module

See Also

Not all variables in a class module can be declared as Public; however, procedures are Public by default, and Property procedures can be used to simulate variables syntactically.  This error has the following causes and solutions:

You declared a Public constant in a class module.

Although you can't declare a Public class-module constant, you can create a Property Get procedure with the same name.  If you don't create a Property Let or Property Set procedure with that name, you are in effect creating a read-only property that can be used the same way you would use a constant.

You declared a Public fixed-length string in a class module.

You can simulate fixed-length strings with a set of Property procedures that either truncate the string data when it exceeds the permitted length, or notify the user that the length has been exceeded.

You declared a Public array in a class module.

Although a procedure cannot return an array, it can return a Variant that contains an array.  To simulate a Public array in a class module, use a set of Property procedures that accepts and returns a Variant containing an array.

You placed a Declare statement in a class module.

Declare statements are implicitly public.  Precede the Declare with the Private keyword.

For additional information, select the item in question and press F1.


 See Also

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement


Member already exists in this form

Identifiers used on forms cannot conflict with names already used by the form.  This error has the following cause and solution:

A procedure or data member identifier in your form, MDI form, or class module uses an identifier already used by the form, MDI form, or class module.  For example, since a form has a BackColor property, the following code would cause this error:

' Form already has a BackColor property.

Dim BackColor As Integer	' Generates the error.

Function BackColor()	' Generates the error.

End Function

Change the identifier that conflicts with the member identifier in your form, MDI form, or class module.

For additional information, select the item in question and press F1.


Event procedure declaration does not match description of event having same name

Your class module has a procedure name that conflicts with the name of an event.  This error has the following cause and solution:

A procedure has the same name as an event, but does not have the same signature (that is, the number and types of the parameters).  This can occur if you do something such as add a new parameter to an event procedure.  For example, if you modify the definition of a form's Form_Load event procedure as follows, this error will occur:

Sub Form_Load (MyParam As Integer)

. . .

End Sub

If the procedure is not the event procedure corresponding to the event, change its name.  If the procedure corresponds to the event, make the parameter list agree with that required by the event (if any).

For additional information, select the item in question and press F1.


Invalid syntax for conditional compiler constant declarations

Entering conditional compiler constants in an Options dialog box differs from declaring constants in code.  This error has the following cause and solution:

You used improper syntax when entering a constant declaration in the Options dialog box.

The only valid syntax is a simple assignment of an integer value to the identifier.  Make sure the syntax for the entry is as follows, with each constant separated by a colon:

constantname = [{+ | [image] }]integervalue : [{+ | [image] }]constantname = integervalue [...]

For additional information, select the item in question and press F1.


User-defined types not allowed as the type of a public member of a class

See Also

You cannot create Public members of Private user-defined types or class modules with Public = False.  This error has the following causes and solutions:

You declared a Public variable (in a class, form, or MDI form module) with the name of a Private user-defined type.

Declare the variable Private, move the Type...End Type statement defining the user-defined type to a standard module, or remove the declaration altogether.

You declared a Public variable (in a class, form, or MDI form module) of a class where the class module's Public property is False.

Declare the variable Private, change the Public property of the class module to True, or remove the declaration altogether.

You tried to define a Public procedure (in a class, form, or MDI form module) with a return type or parameter having the type of a Private user-defined type.

Declare the procedure Private, move the Type...End Type statement defining the user-defined type to a standard module, or remove the declaration altogether.

You tried to define a Public procedure (in a class, form, or MDI form module) with a return type or parameter having the type of a class module whose Public property is False.

Declare the procedure Private, change the Public property of the class module to True, or remove the declaration altogether.

For additional information, select the item in question and press F1.


 See Also

Private Statement

Public Statement

Type Statement


Invalid Next control variable reference

See Also

The numeric variable in the Next part of a For...Next loop must match the variable in the For part.  This error has the following cause and solution:

The variable in the Next part of a For...Next loop differs from the variable in the For part.  For example:

For Counter = 1 To 10

MyVar = Counter

Next Count

Check the spelling of the variable in the Next part to be sure it matches the For part.  Also, be sure you have not inadvertently deleted parts of the enclosing loop that may have used the variable.

For additional information, select the item in question and press F1.


 See Also

For...Next Statement

For Each...Next Statement


Variable not yet created in this context

A variable has to be created before it can be displayed in the Watch window or the Immediate window, and before it can have values assigned to it in the Immediate window.  This error has the following causes and solutions:

You tried to display the value of a local variable that you just entered in your code before executing at least a Single Step command in break mode.

Choose the Step Into command from the Run menu to force compilation of the new statement.

You tried to display the value of a local variable that you just added in a procedure farther down the call chain by moving to the procedure using the Calls dialog box.

You have to actually return to the procedure before you can display the variable in its context.

For additional information, select the item in question and press F1.


A module is not a valid type

See Also

A standard module doesn't represent a class and cannot be instantiated in the form of a variable.  This error has the following cause and solution:

You used the name of a standard module in a Dim or Set declaration.

Check the spelling of the module name and make sure it corresponds to a form, MDI form, or class module.

For additional information, select the item in question and press F1.


 See Also

Dim Statement

Set Statement


OLE type not supported in Visual Basic

See Also

Not all OLE types are supported in Visual Basic.  This error has the following cause and solution:

You tried to use a type in your program that has no equivalent in Visual Basic for applications.  For example, Visual Basic has no ENUM type, so if you try to create a variable with the type of an ENUM from an object library, this error occurs.  In the example that follows, even though Rainbow may be a valid enumeration, Visual Basic cannot create a variable of that type:

Dim MyVar As Rainbow	' Causes error.

If ENUM is a valid parameter type for a function in an object library, this error means only that you cannot create a variable of that type in your own code.  Although you cannot always declare variables with a data type specified in an object's documentation, there is often a Visual Basic equivalent.  For example, you can simulate enumerations with Integer variables or with a series of symbolic constants declared with the Const statement.  Also, check the Variant type's subtypes.  You can often use them as equivalents of types not offered directly in Visual Basic.  In some cases, however, Visual Basic simply has no equivalent.  For example, pointer types are not available.

For additional information, select the item in question and press F1.


 See Also

Const Statement

Data Type Summary


Function marked as restricted or uses an OLE type not supported in Visual Basic

Not every procedure that appears in a type library or object library can be accessed by every programming language.  The creator of a type or object library can designate some functions as restricted to prevent their use by macro languages.  This error has the following causes and solutions:

You tried to use a function with a restricted specification.

You cannot use the function in your program.  If you have documentation for the object represented by the library, check it to see if a method is provided that gives equivalent functionality.

You tried to use a function that needs a parameter type or has a return type that is not available in Visual Basic.  For example, you cannot use functions that expect the RECORD type as a parameter or return type.

Sometimes you can simulate return types with Visual Basic equivalents.  Check the subtypes of the Variant data type.  This may also work for non-Basic parameter types that are expected as references.  However, you cannot pass a Variant data type by value in an effort to simulate a non-Basic type.

For additional information, select the item in question and press F1.


Variable uses an OLE type not supported in Visual Basic

Not every variable that appears in a type library or object library can be used by every programming language.  This error has the following cause and solution:

You tried to use a variable defined in a type or object library that has a data type that is not supported by Visual Basic.

You cannot use a variable of a type not recognized by Visual Basic in a Visual Basic program.

For additional information, select the item in question and press F1.


Can't define a Public user-defined type within a class

See Also

A user-defined type that appears within a form, MDI form, or class module cannot be Public.  This error has the following cause and solution:

In a form, MDI form, or class module, you tried to define a Public user-defined type.

Move the user-defined type definition to a standard module, then declare variables of the type in the class module or other modules, as appropriate.  If you only want the type to be available in the module in which it appears, you can place its Type...End Type definition in the form, MDI form, or class module and precede its definition with the Private keyword.

{

For additional information, select the item in question and press F1.


 See Also

Private Keyword

Type Statement


A compatible OLE server must be a Visual Basic executable

A compatible OLE object is one that you specify as a Compatible OLE server.  This error has the following cause and solution:

Visual Basic tried to access an object you specified as a compatible OLE server, but the file specified was not an executable file created by Visual Basic.

Only .EXE files created by Visual Basic are valid entries in the Compatible OLE Server field of the Options dialog box accessed through the Tools menu.  If possible, load the project into Visual Basic and choose the Make EXE File command from the File menu to create a Visual Basic executable file.  If the file is already an executable file that was not created by Visual Basic, or if it cannot be loaded into Visual Basic, consult the documentation of the file to find out if it can be converted to a Visual Basic executable file or if the vendor can supply an executable file created by Visual Basic.

For additional information, select the item in question and press F1.


Calling convention not supported by Visual Basic

Visual Basic does not support all procedure calling conventions, which specify the order in which arguments must be passed and the way in which argument types must be specified.  This error has the following cause and solution:

The procedure was called using a calling convention that Visual Basic does not support.  For example, Visual Basic does not support the Pascal calling convention in a 16-bit version of the Microsoft Windows environment.

If the calling convention is not supported by Visual Basic, the procedure cannot be called from Visual Basic.  Check the object's documentation to see if an alternative is provided.

For additional information, select the item in question and press F1.


The specified region has been searched and "|" replacements were made

When you choose the Replace All button in the Replace dialog box, this message specifies the total number of replacements.  This condition has the following cause and effect:

When doing a search and replace operation, you can specify the region to be covered [image] selection, procedure, module, or project.

If a region is selected, it is the default search region.  If no region is selected, the current module is the default search region.  To change the scope of a search, select a different option in the Replace dialog box.

For additional information, select the item in question and press F1.


The specified region has been searched

When you choose the Find Next and Replace buttons in the Replace dialog box, the total number of replacements is not specified.  This condition has the following cause and effect:

When doing a search and replace operation, you can specify the region to be covered [image] selection, procedure, module, or project.

If a region is selected, it is the default search region.  If no region is selected, the current module is the default search region.  To change the scope of a search, select a different option in the Replace dialog box.

For additional information, select the item in question and press F1.


The specified region has been searched and 1 replacement was made

When you choose the Replace All button in the Replace dialog box, this message specifies the total number of replacements.  This condition has the following cause and effect:

During the search and replace operation, only one instance of the specified text was found, and the replacement was made.  You can specify the region to be covered [image] selection, procedure, module, or project.

If a region is selected, it is the default search region.  If no region is selected, the current module is the default search region.  To change the scope of a search, select a different option in the Replace dialog box.

For additional information, select the item in question and press F1.


Can't add a reference to the specified file

Not all object libraries or type libraries can be accessed by Visual Basic.  This error has the following cause and solution:

You tried to use the Add References dialog box to add a reference to a type or object library that cannot be used by Visual Basic.

Check the documentation for the object represented by the library to see if it is available in some other form that Visual Basic can use.

For additional information, select the item in question and press F1.


The edit may make the class module incompatible with the previously specified compatible object application
The edit may make the class module incompatible with the previously specified compatible OLE server

If a compatible OLE server already exists as an executable file, you must be careful not to change its interface.  This warning has the following cause and solution:

You are trying to edit the code of a class module that already is represented by an executable file.

If you make changes that affect the interface to the object, code that has been written against the object may fail.  Although you can enhance new versions of an object that you have previously released, you must be sure that the interface to the object is the same so that code previously written against the object will still work as expected.

In Visual Basic, the name of the compatible OLE server appears in the dialog box displayed when you choose Project Options from the Tools menu.

Important   If you want to accept the edit, choose OK in the error message dialog box.  If you want to undo the edit, choose the Cancel button.

For additional information, select the item in question and press F1.


OLE Automation server can't create object
OLE Automation server can't create object or return reference to this object (Error 429)

See Also

Creating objects requires that the object's class be registered in the system registry and that any associated dynamic-link libraries (DLLs) be available.  This error has the following causes and solutions:

The class is not registered.  For example, the system registry has no mention of the class, or the class is mentioned, but specifies either a file of the wrong type or a file that cannot be found.

If possible, try to start the object's application.  If the registry information is out of date or wrong, the application should check the registry and correct the information.  If starting the application doesn't fix the problem, rerun the application's setup program.

A DLL required by the object cannot be used, either because it can't be found or it was found, but was corrupted.

Make sure all associated DLLs are available.  For example, an object like the Data Access Object (DAO) needs supporting DLLs that vary among platforms.  You may have to rerun the setup program for such an object if that is what is causing this error.

The object is available on the machine, but it is a licensed OLE object, and cannot verify the availability of the license necessary to instantiate it.

Some objects can only be instantiated only after the server finds a license key, which verifies that the object is registered for instantiation on the current machine.  When a reference is made to an object through a properly installed type or object library, the correct key is supplied automatically.  But if the attempt to instantiate is the result of a CreateObject or GetObject call, the object must find the key.  In this case, it may search the system registry, or look for a special file (for example, one with the extension .LIC) that it creates when it is installed.  If the key cannot be found, the object cannot be instantiated.  If an end user has improperly set up the object's application, inadvertently deleted a necessary file, or changed the system registry, the object may not be able to find its key.   If the key cannot be found, the object cannot be instantiated.  In this case, the instantiation may work on the developer's system, but not on the system of the user.  It may be necessary for the user to reinstall the licensed object.

You are trying to use the GetObject function to retrieve a reference to a class created with Visual Basic.

GetObject cannot be used to obtain a reference to a class created with Visual Basic.

Access to the object has explicitly been denied.

You may be trying, for example,  to access a data object that is currently being used and is locked to prevent deadlock situations. If that is the case, you may be able to access the object at another time.

For additional information, select the item in question and press F1.


See Also

CreateObject Function

GetObject Function


Too many local, nonstatic variables

See Also

Local, nonstatic variables are variables that are defined within a procedure and  are reinitialized each time the procedure is called.  This error has the following cause and solution:

The sum of the memory requirements for this procedure's local, nonstatic variables (and compiler-generated temporary variables) exceeds 32K.

Declare some of your variables with the Static statement where appropriate.  Static variables retain their value between procedure invocations because they are allocated from different memory resources than nonstatic variables.

For additional information, select the item in question and press F1.


 See Also

Static Statement


Too many module-level variables

See Also

Module-level variables are those declared in the declarations section of a module, before the module's procedures.  This error has the following cause and solution:

The sum of the memory requirements for all module-level variables in this module exceeds 64K.

This is the storage limit for this module.  If appropriate, you can declare some of your variables as Public in another module, or if some module-level variables are used only in one procedure, you can declare them within that procedure.  If you have declared variables at module level because you want them to retain their value between procedure invocations, you can instead declare them as Static within the procedure in which they are referenced.

Note   Available space can vary among operating systems.

For additional information, select the item in question and press F1.


See Also

Public Statement

Static Statement


Module too large

See Also

A module contains code within the project.  This error has the following cause and solution:

There is too much code in the module.

Create a new module, and move some of the procedures from this module to the new one.  If the current module contains module-level declarations of data that must be visible to the procedures in the new module, declare that data as Public.

Note   Comments are not counted as lines of code.  Therefore, deleting comments does not prevent this error.

For additional information, select the item in question and press F1.


 See Also

Public Statement


Procedure too large

When compiled, the code for a procedure cannot exceed 64K.  This error has the following cause and solution:

Code for this procedure exceeds 64K when compiled.

Break this, and any other large procedures, into two or more smaller procedures.

For additional information, select the item in question and press F1.


Insufficient Immediate pane memory to create variable

Memory in the Immediate pane is limited.  This error has the following cause and solution:

You specified a variable in the Immediate pane that has to be instantiated, since it hasn't been created in the program's code context.

Delete the reference to the variable in the Immediate pane, or declare the variable in the program's code context so that it doesn't have to be created in the Immediate pane.

For additional information, select the item in question and press F1.


#ElseIf must be preceded by a matching #If or #ElseIf and followed by an #ElseIf, #Else, or #End If

See Also

#ElseIf is a conditional compilation directive.  This error has the following causes and solutions:

An #ElseIf has been detected that is not preceded by an #If or #ElseIf.

Place an #If statement before the #ElseIf or remove any incorrectly placed preceding #End If.

An #ElseIf has been detected that is preceded by an #Else or #End If.

Appropriately terminate the preceding #If block, or change the preceding #Else to an #ElseIf.

For additional information, select the item in question and press F1.


 See Also

If...Then...Else Statement

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


#Else clause must be preceded by a matching #If

See Also

#Else is a conditional compilation directive.  This error has the following cause and solution:

An #Else clause was detected that is not preceded by a matching #If or #ElseIf.

Check to see if a preceding #If has been separated from this #Else by an #End If.  Also, note that only one #Else is permitted in each #If block, so two successive #Else clauses cause this error.

For additional information, select the item in question and press F1.


 See Also

If...Then...Else Statement

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


You must terminate the #If block with an #End If

See Also

#If is a conditional compilation directive.  This error has the following cause and solution:

An #If block was detected that is not terminated by an #End If.

Add an #End If in the appropriate position.

For additional information, select the item in question and press F1.


 See Also

If...Then...Else Statement

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


#Else If, #Else, or #End If must be preceded by a matching #If

See Also

#Else If, #Else, and #End If are conditional compilation directives.  This error has the following cause and solution:

An #Else If, #Else, or #End If was detected that is not preceded by a matching #If clause.

Check to see if the intended #If has been separated from the clause in question by an intervening block or if the intended #If has its # sign.  If everything else is in order, place an #If clause in the appropriate position.

For additional information, select the item in question and press F1.


 See Also

If...Then...Else Statement

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


Invalid property value (Error 380)

Most properties only accept values of a certain type, within a certain range.  This error has the following cause and solution:

An inappropriate value has been assigned to a property.

See the property's Help topic to determine what types and range of values are appropriate for the property.

For additional information, select the property in question and press F1.


Invalid picture (Error 481)

Only a picture can be assigned to the Picture property or Picture object.  This error has the following cause and solution:

You attempted to assign something to a Picture property (of a form or PictureBox control, for example) or a Picture object that is not recognized as an icon, bitmap, or Microsoft Windows metafile.

See the Help topics for the Picture object or Picture property of the object you are using to determine the acceptable picture types.

For additional information, select the item in question and press F1.


Invalid format in resource file (Error 325)

When accessing a resource file, the resource you are trying to retrieve must have a valid format.  This error has the following cause and solution:

The resource file you are trying to retrieve has an invalid format, or a specific resource in the file has an invalid format.

If the file contents have been damaged, reinstall the file from its original disk.  If the error continues, contact the provider of the resource for a new file or a version of the resource with the expected format.

For additional information, select the item in question and press F1.


Project contains too many procedure, variable, and constant names

A project's procedure, variable, constant, and parameter names are stored in a name table  This error has the following cause and solution:

The number of names in the project's name table exceeds 32,768.

The name table may contain some temporary duplicates. You can compact the name table by saving the project to a disk, then closing it.  If the problem persists after you reopen the project, reduce the number of names by reusing local variable names in multiple procedures, then recompact the table by saving the project, closing it, and reopening it.

For additional information, select the item in question and press F1.


Option Private Module not permitted in Class module

See Also

Option Private Module makes the contents of a module unavailable to other projects, while preserving their availability to your project.  This error has the following cause and solution:

The statement  Option Private Module appears in a class module.

Remove the Option Private Module statement from the class module.  Visual Basic class modules have the characteristic of Option Private Module by default. This can only be changed by setting the Public property to True on the class module's Property window.  This cannot be done from code: it can only be done with Visual Basic, Professional Edition [image] it is required for creating public OLE Automation objects.

For additional information, select the item in question and press F1.


See Also

OLE Automation

OptionPrivate Statement


Duplicate key (Error 457)

See Also

A key is a string (specified in the Add method) that uniquely identifies a specific member of a collection.  This error has the following cause and solution:

You are specifying a key for a collection member that already identifies another member of the collection.

Choose a different key for this member.

For additional information, select the item in question and press F1.


See Also

Add Method


This array is fixed or temporarily locked (Error 10
This array is fixed or temporarily locked (Error 10)

See Also

Not all arrays can be redimensioned.  Even arrays specifically declared to be dynamic (and arrays within Variant variables) are sometimes locked temporarily.  This error has the following causes and solutions:

You tried to use ReDim to change the number of elements of a fixed-size array.  For example, in the following code, the fixed array FixedArr is received by SomeArr in the procedure NextOne, then an attempt is made to resize SomeArr:

Sub FirstOne

Dim FixedArr(25) As Integer	' Create a fixed-size array and

NextOne FixedArr()	' pass it to another procedure.

End Sub

Sub NextOne(SomeArr() As Integer)

ReDim SomeArr(35)	' Error 10 occurs here.

. . .

End Sub

Make the original array dynamic, rather than fixed, by declaring it with ReDim  (if it is declared within a procedure), or by declaring it without specifying the number of elements (if it is declared at module level).

You tried to redimension a module-level dynamic array, one of whose elements has been passed as an argument to a procedure.  For example, in the following code, ModArray is a dynamic, module-level array whose forty-fifth element is being passed by reference to the Test procedure:

Dim ModArray () As Integer	' Create a module-level dynamic array.

. . .

Sub AliasError()

ReDim ModArray (1 To 73) As Integer

Test ModArray (45)	' Pass an element of the module-level

' array to the Test procedure.

End Sub

Sub Test(SomeInt As Integer)

ReDim ModArray (1 To 40) As Integer  ' Error occurs here.

End Sub

There is no need to pass an element of the module-level array in this case, since it is visible within all procedures in the module.  However, if an element is passed, the array is locked to prevent the situation where the memory for the reference parameter is deallocated within the procedure, causing unpredictable behavior when the procedure returns.

You attempted to assign a value to a Variant variable containing an array, but the Variant is currently locked. For example, if your code uses a For Each...Next loop to iterate over a variant containing an array, the array is locked on entry into the loop, then released at the termination of the loop:

SomeArray = Array(9,8,7,6,5,4,3,2,1)

For Each X In SomeArray

SomeArray = 301	' Causes error since array is locked.

Next X

Use a For...Next (rather than a For Each...Next) loop to iterate.  When an array is the object of a For Each...Next loop, you can read it, but not write to it.

For additional information, select the item in question and press F1.


See Also

For...Next Statement

For Each...Next Statement

ReDim Statement

Sub Statement

Variant Data Type


Connection to type library or object library for remote process has been lost

See Also

During remote access (that is, when accessing an object that is part of another process, or running on another machine) the connection to the library containing object information was broken.  This error has the following cause and solution:

You lost your connection to the remote process's object library or type library.

To reconnect, follow these steps:

1.	Restart the Application object.

2.	In the error dialog box through which you entered this Help topic, click OK to display the References dialog box.

3.	The lost reference appears with the word MISSING to its left.

4.	Remove the lost reference.

5.	The dialog box also contains a reference for the object you started in step 1. Click its check box.

For additional information, select the item in question and press F1.


See Also

OLE Automation


Method not valid without suitable object

See Also

Not all methods can be performed by all objects.  This error has the following cause and solution:

You have called a method without specifying an object, and the method is not valid for the implicit object.  For example, you cannot use the Line method in a standard module without a valid object qualifier because a standard module cannot display the output of the Line method.

Explicitly qualify the method call with an object that can accept the method. For example, with the Line method, you can specify a form or picture box.

Note   Other methods that need an explicit object qualifier when used in a standard module include Circle, Print, and PSet.

For additional information, select the item in question and press F1.


See Also

Circle Method

Line Method

Print Method

Pset Method


Please see the Readme file for more information on this error

Some error messages were added to this product after Help was completed.  Help explanations for these errors can be found in the Readme file.

For additional information, select the item in question and press F1.


Definitions of property procedures for the same property are inconsistent or contain optional parameters or a ParamArray
Definitions of property procedures for the same property are inconsistent, or contain optional parameters or a ParamArray.

See Also

The parameters for Property Get, Property Let, and Property Set procedures for the same property must match exactly, except that the Property Let has one extra parameter, whose type must match the return type of the corresponding Property Get, and the Property Set has one more parameter than the corresponding Property Get, whose type is either Variant, Object, a class name, or an object library type specified in an object library.  This error has the following causes and solutions:

The number of parameters for the Property Get procedure is not one less than the number of parameters for the matching Property Let or Property Set procedure.

Add a parameter to the Property Let or Property Set, or remove a parameter from the Property Get, as appropriate.

The parameter types of the Property Get must exactly match those of the corresponding parameters of the Property Let or Property Set (except for the latter's extra parameter).

Modify the parameter declarations in the corresponding procedure definitions so they are appropriately matched.

The parameter type of the extra parameter of the Property Let must match the return type of the corresponding Property Get procedure.

Modify either the extra parameter declaration in the Property Let or the return type of the corresponding Property Get so they are appropriately matched.

The parameter type of the extra parameter of the Property Set can differ from the return type of the corresponding Property Get, but it must be either a Variant, Object, class name, or a valid object library type.

Make sure the Property Set procedure's extra parameter is either a Variant, Object, class name, or object library type.

You've defined a Property procedure with an Optional or a ParamArray parameter.

ParamArray and Optional parameters are not permitted in Property procedures.  Redefine the procedures without using these keywords.

For additional information, select the item in question and press F1.


See Also

Object Data Type

Property Get Statemenet

Property Let Statemenet

Property Set Statemenet

Variant Data Type


Can't create necessary temporary file
Cannot create necessary temporary file

Creating an executable file requires creation of temporary files.  This error has the following cause and solution:

The drive that contains the directory specified by the TEMP environment variable is full.

Delete files from the full drive or specify a different drive in the TEMP environment variable.

Your TEMP environment variable specifies an invalid or read-only drive or directory.

Specify a valid drive for the TEMP environment variable or remove the read-only restriction from the currently specified drive or directory.

For additional information, select the item in question and press F1.


Filename or class name not found during OLE Automation operation (Error 432)

The GetObject function requires either a valid filename with a path specification, or the name of a class that is registered with the system.  This error has the following cause and solution:

The name specified for filename or class in a call to the GetObject function could not be found.

Check the names and try again.  Make sure the name used for class matches that registered with the system.

For additional information, select the item in question and press F1.


OLE Automation object does not have a default value (Error 443)

When you specify an object name without a property or method, Visual Basic assumes you are referencing the object's default member (property or method).  However, not all objects expose a default member.  This error has the following cause and solution:

Visual Basic cannot determine the default member for the specified object.

Check the object's documentation and give an explicit specification for the property or method.

For additional information, select the item in question and press F1.


The .VBP file for this project contains an invalid or corrupt library references ID
The .VBP file for this project contains an invalid or corrupted library references ID

When you save a project for which a reference has been selected from the References dialog box, an entry is made in the project's .VBP file (called the .MAK file in earlier versions of Visual Basic).  For example, the entry for a data access object is:

Reference=*\G{00025E01-0000-0000-C000-000000000046}#0.0#0#C:\WINDOWS\SYSTEM\DAO2516.DLL#Microsoft

DAO 2.5 Object Library

This error occurs when such a reference has been edited or corrupted.  This error has the following cause and solution:

A reference in the .VBP file has become invalid.

Delete the incorrect line from the .VBP file, then check the appropriate object library in the Tools menu's References dialog box. Then save the project, and the correct information will be entered in the .VBP file.

For additional information, select the item in question and press F1.


Circle Method

See Also	Example	Applies To

Draws a circle, ellipse, or arc on an object.  Doesn't support named arguments.

Syntax

object.Circle Step (x, y), radius, color, start, end, aspect

The Circle method syntax has the following parts.

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form with the focus is assumed to be object.

Step	Optional.  A keyword specifying 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)	Required.  Single-precision values indicating the coordinates for the center point of the circle, ellipse, or arc.  The ScaleMode property of object determines the units of measure used.

radius	Required.  Single-precision value indicating the radius of the circle, ellipse, or arc.  The ScaleMode property of object determines the unit of measure used.

color	Optional.  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	Optional.  Single-precision values.  When an arc or 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	Optional.  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.

Remarks

To fill a circle, set the FillColor and FillStyle properties of the object on which 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 setting of 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, 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 an optional trailing argument, don't use any commas following the last argument you specify.

When Circle executes, the CurrentX and CurrentY properties 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

Line Method

QBColor Function

RGB Function

ScaleMode Property

Shape Control


Circle Method Applies To

Form Object

PictureBox Control

Printer Object


Command Function

See Also	Example

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

Syntax

Command

Note   For Visual Basic in-process OLE server (DLL) considerations and restrictions that apply to this topic, see Make OLE DLL File Command.

Remarks

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

VB /CMD cmdlineargs

For applications developed with Visual Basic and compiled to an .EXE file, Command returns any 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 Options from the Tools menu.


See Also

Make OLE DLL File Command

Returning Strings from Functions


Line Method

See Also	Example	Applies To

Draws lines and rectangles on an object.  Doesn't support named arguments.

Syntax

object.Line Step (x1, y1) - Step (x2, y2), color, BF

The Line method syntax has the following parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form with the focus is assumed to be object.

Step	Optional.  A keyword specifying that the starting point coordinates are relative to the current graphics position given by the CurrentX and CurrentY properties.

(x1, y1)	Optional.  Single-precision values indicating the coordinates of the starting point for the line or rectangle.  The ScaleMode property determines the unit of measure used.  If omitted, the line begins at the position indicated by CurrentX and CurrentY.

Step	Optional.  A keyword specifying that the end point coordinates are relative to the line starting point.

(x2, y2)	Required.  Single-precision values indicating the coordinates of the end point for the line being drawn.

color	Optional.  Long integer value indicating the RGB color used to draw the line.  If omitted, the ForeColor property setting is used.  You can use the RGB function or QBColor function to specify the color.

B	Optional.  If included, causes a box to be drawn using the coordinates to specify opposite corners of the box.

F	Optional.  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.

Remarks

To draw connected lines, begin a subsequent line at the end point of the previous line.

The width of the line drawn depends on the setting of 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, the CurrentX and CurrentY properties are set to the end point specified by the arguments.


See Also

Circle Method

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

ForeColor Property

QBColor Function

RGB Function

ScaleMode Property

Shape Control


Line Method Applies To

Form Object

PictureBox Control

Printer Object


PSet Method

See Also	Example	Applies To

Sets a point on an object to a specified color. Doesn't support named arguments.

Syntax

object.PSet Step (x, y), color

The PSet method syntax has the following parts:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.  If object is omitted, the Form with the focus is assumed to be object.

Step	Optional.  A keyword specifying that the coordinates are relative to the current graphics position given by the CurrentX and CurrentY properties.

(x, y)	Required.  Single-precision values indicating the horizontal (x-axis) and vertical (y-axis) coordinates of the point to set.

color	Optional.  Long integer value indicating the RGB color specified for point.  If omitted, the current ForeColor property setting is used.  You can use the RGB function or QBColor function to specify the color.

Remarks

The size of the point drawn depends on the setting of 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, the CurrentX and CurrentY properties 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 the BackColor property setting as the color argument.


See Also

BackColor, ForeColor Properties

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

QBColor Function

RGB Function


PSet Method Applies To

Form Object

PictureBox Control

Printer Object


Err Object

See Also 	Example	Properties	Methods

Contains information about run-time errors.  Accepts the Raise and Clear methods for generating and clearing run-time errors.

Syntax

Err[.{property | method}]

Remarks

The properties of the Err object are set by the generator of an error [image] Visual Basic, an OLE object, or the Visual Basic programmer.

The default property of the Err object is Number.  Its value corresponds to the value returned by the Err function in previous versions of Visual Basic.  Assigning an error code to the Number property corresponds to specifying a number in the Err statement in previous versions of Visual Basic.  Since the default property can be represented by the object name Err, existing code that expects a valid error number to be returned or set by Err doesn't have to be modified.  While the value of Err.Number is compatible with previous versions of Basic, it now contains a Long integer and can be used by an OLE Automation object to return an OLE SCode.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it.  To generate a run-time error in your code, use the Raise method.

The Err object's properties are reset to zero or zero-length strings ("") after any form of the Resume or On Error statement and after an Exit Sub, Exit Function, or Exit Property statement within an error-handling routine.  The Clear method can be used to explicitly reset Err.

Caution   If you set up an error handler using On Error GoTo and that handler calls another procedure, the properties of the Err object may be reset to zero and zero-length strings.  To retain values for later use, assign the values of Err properties to variables before calling another procedure, or before executing Resume, On Error, Exit Sub, Exit Function, or Exit Property statements.

When writing code for an OLE Automation object in Visual Basic, use the Raise method (rather than the Error statement) to generate run-time errors.  Whether or not to use the Raise method in new non-OLE Automation code depends on the richness of the information you want to return.  In code that uses Error statements instead of the Raise method to generate errors, the properties of the Err object are assigned the following default values when Error is executed:

Property	Value

Number	Value specified as argument to Error statement.  Can be any valid error number.

Source	Name of the current Visual Basic project.

Description	A string corresponding to the return of the Error function for the specified Number, if this string exists.  If the string doesn't exist, Description contains "Application-defined or object-defined error".

HelpFile	The fully qualified drive, path, and filename of the Visual Basic Help file.

HelpContext	The Visual Basic Help file context ID for the error corresponding to the Number property.

LastDLLError	On 32-bit Microsoft Windows operating systems only, contains the system error code for the last call to a dynamic-link library (if theDLL supports this functionality).  The LastDLLError property is read-only.

There is no need to change existing code that used Err and the Error statement.  However, mixing use of the Err object and the Error statement can result in unintended consequences.  For instance, even if you fill in the Err object's properties, they are reset to the default values indicated in the preceding table as soon as the Error statement is executed.  Although you can still use the Error statement to generate Visual Basic run-time errors, it is retained principally for compatibility with existing code.  Use the Err object and the Raise and Clear methods for system errors and in new code, especially for OLE Automation objects.

The Err object is an intrinsic object with global scope [image] there is no need to create an instance of it in your code.


 See Also

Error Function

Error Object, Errors Collection

Error Statement

On Error Statement

Resume Statement

Trappable Errors


Err Object Properties

Description Property

HelpContext Property

HelpFile Property

LastDLLError Property

Number Property

Source Property


Err Object Methods

Clear Method

Raise Method


Number Property

See Also	Example	Applies To

Returns or sets a numeric value specifying an error.  Number is the Err object's default property.

Syntax

object.Number [= errornumber]

The Number property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

errornumber	A Long integer representing a Basic error number or an OLE SCode error value.

Remarks

Because the Number property is the Err object's default property, existing code that uses the Err function does not have to be revised.  All of the following correctly return or set the Number property:

Err.Number = 5	' Set the Err object's Number property to 5.

Err = 5	' Set the Err object's Number property to 5.

Debug.Print Err	' Display the Err object's Number property.

Debug.Print Err.Number	' Display the Err object's Number property.

When returning a user-defined error from an OLE Automation object, set Err.Number by adding the number you've chosen as an error code to the constant vbObjectError.  For example, you use the following code to return the number 1051 as an error code:

Err.Raise Number := vbObjectError + 1051, Source:= "SomeClass"

Not all Visual Basic host applications can create OLE Automation objects.  See your host application's documentation to determine whether it can create classes and OLE Automation objects.  However, all host applications can create OLE Automation controllers, and should use code like the following when interpreting error codes returned from objects:

If Err.Number = vbObjectError + 1051 Then	' Code to trap a specific

...	' VB object error.

ElseIf Err.Number - vbObjectError > 0 Then	' Other Visual Basic

If Err.Number - vbObjectError < 65535 Then	' object-generated errors

' are between 0-65535.

...	' Code to handle Visual

End If	' Basic object errors.

ElseIf Err.Number > 0 Then	' If a VB object returns

If Err.Number < 65535 Then	' a system-defined error,

...	' there is no need to

End If	' strip vbObjectError.

End If

The first If traps a specific object-defined error by combining it with the constant vbObjectError.  Action can then be taken for the object's error number 1051.  The first ElseIf traps a range of object-defined errors. It subtracts vbObjectError from Err.Number, then examines the result to see if it is in the range for an object-defined error.  If it is, the action taken should depend on the documentation of the error provided by the object.  The final ElseIf checks to see if the error is simply a Visual Basic trappable runtime error (a system error), for example File not found (Error 53) that may have been passed back by the object.  Note that although the range for these is 0 - 65535, the actual number of defined errors is currently fewer than 1000.

Since Number is a property, it behaves like a function call, and this may be significant if Err is passed to a procedure.  If you have existing code in which you rely on a change in Err being copied back to the caller through the procedure's parameter, it may fail even if Err is passed ByRef.  However, since Err is a global object, there is no need to pass it as an argument at all.  Make any desired changes directly to Err or Err.Number in the called procedure.


 See Also

Description Property

Err Object

HelpContext Property

HelpFile Property

Source Property


Number Property Applies To

Err Object


Source Property

See Also	Example	Applies To

Returns or sets the name of the object or application that originally generated the error.

Syntax

object.Source [= stringexpression]

The Source property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

stringexpression	A string expression representing the application that generated the error.

Remarks

The Source property specifies a string expression representing the object that originally generated the error; the expression is usually the object's class name or programmatic ID.  Use Source to provide your users with information when your code is unable to handle an error generated in an accessed object.  For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application.  Note that if the error is generated in another object called by Microsoft Excel, Microsoft Excel intercepts the error and sets Err.Number to its own code for Division by zero.  However, it leaves the other Err object properties (including Source) as set by the object that generated the error.  Source always contains the name of the object that originally generated the error [image] your code can try to handle the error according to the error documentation of the object you accessed.  If your error handler fails, you can use the Err object information to describe the error to your user, using Source and the other Err properties to inform the user which object originally caused the error, its description of the error, and so forth.

When generating an error from code, Source is your application's programmatic ID.  For OLE Automation class modules, Source should contain a name having the form project.class.

Note   The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects.  Checking Err after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred.  Thus, you can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the one specified in Err.Source).


 See Also

Description Property

GetObject Function

HelpContext Property

HelpFile Property

Number Property

On Error Statement


Source Property Applies To

Err Object


HelpFile Property

See Also	Example	Applies To

Returns or sets a fully qualified path to a Microsoft Windows Help file.

Syntax

object.HelpFile [= pathspec]

The HelpFile property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

pathspec	Fully qualified path to the Help file.

Remarks

If a Microsoft Windows Help file is specified in HelpFile, it is automatically called when the user presses the Help button (or the F1 key) in the error message dialog box.  If the HelpContext property contains a valid context ID for the specified file, that topic is automatically displayed.  If no HelpFile is specified, then the Visual Basic Help file is displayed.

Note   You should write routines in your application to handle typical errors.  When programming with an object, you can use the Help supplied by the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable.  When writing OLE Automation objects, you should tailor your Help to programmers programming with your object, as well as supply meaningful information to an end user for an unrecoverable error.


 See Also

Description Property

HelpContext Property

Number Property

Source Property


HelpFile Property Applies To

Err Object


HelpContext Property

See Also	Example	Applies To

Returns or sets a context ID for a topic in a Microsoft Windows Help file.

Syntax

object.HelpContext [= contextid]

The HelpContext property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

contextid	A valid identifier for a Help topic within the Help file.

Remarks

If a Microsoft Windows Help file is specified in HelpFile, the HelpContext property is used to automatically display the Help topic it identifies.  If both HelpFile and HelpContext are empty, the value of Number is checked, and, if it corresponds to a Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used.  If the Number value does not correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed.

Note   You should write routines in your application to handle typical errors.  When programming with an object, you can use the Help supplied by the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error is not recoverable.  When writing OLE Automation objects, you should tailor your Help to programmers programming with your object, as well as supply meaningful information to an end user for an unrecoverable error.


 See Also

Description Property

HelpFile Property

Number Property

Source Property


HelpContext Property Applies To

Err Object


Description Property

See Also	Example	Applies To

Returns or sets a descriptive string associated with an error.

Syntax

object.Description [= stringexpression]

The Description property syntax has these parts:

Part	Description

object	An object expression that evaluates to an object in the Applies To list.

stringexpression	A string expression containing a description of the error.

Remarks

The Description property comprises a short description of the error.  Use this property to alert the user to an error that you cannot or do not want to handle.  When generating a user-defined error, assign a short description of your error to this property.  If Description is not filled in, and the value of Number corresponds to a Visual Basic run-time error, the string returned by the Error function is placed in Description when the error is generated.


 See Also

Error Function

Error Object, Errors Collection

HelpContext Property

HelpFile Property

Number Property

Source Property


Description Property Applies To

Err Object


Clear Method (Err Object)
Clear Method

See Also	Example	Applies To

Clears all property settings of the Err object.

Syntax

object.Clear

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

Use Clear to explicitly clear the Err object after an error has been handled.  This is necessary, for example, when you use deferred error handling with On Error Resume Next.  Visual Basic calls the Clear method automatically whenever any of the following statements is executed:

Any type of Resume statement

Exit Sub, Exit Function, Exit Property

Any On Error statement

Clear is equivalent to Err = 0 in previous Basic products.

Note   The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects.  Checking Err after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred.  Thus, you can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the one specified in Err.Source).


 See Also

Description Property

HelpContext Property

HelpFile Property

Number Property

On Error Statement

Raise Method

Source Property


Applies To

Err Object


Raise Method

See Also	Example	Applies To

Generates a run-time error.

Syntax

object.Raise(Number, Source, Description, HelpFile, HelpContext)

The Raise method has the following object qualifier and named arguments:

Argument	Description

object	An object expression that evaluates to an object in the Applies To list.

Number	Required.  A Long integer that identifies the nature of the error.  Visual Basic errors (both Visual Basic-defined and user-defined errors) are in the range 0 [image] 65535. When setting the Number property to your own error code in an OLE Automation object, you add your error code number to the constant vbObjectError.  For example, to generate the error number 1050, assign vbObjectError + 1050 to the Number property.

Source	Optional.  A string expression naming the object or application that originally generated the error.  When setting this property for an OLE Automation object, use the form project.class.  If nothing is specified, the programmatic ID of the current Visual Basic project is used.

Description	Optional.  A string expression describing the error.  If unspecified, the value in Number is examined.  If it can be mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as Description.  If there is no Visual Basic error corresponding to Number, "Application-defined or object-defined error" is used.

HelpFile	Optional.  The fully qualified path to the Microsoft Windows Help file in which help on this error can be found.  If unspecified, Visual Basic uses the fully qualified drive, path, and filename of the Visual Basic Help file.

HelpContext	Optional.  The context ID identifying a topic within HelpFile that provides help for the error.  If omitted, the Visual Basic Help file context ID for the error corresponding to the Number property is used, if it exists.

Remarks

All the arguments are optional except Number.  If you use Raise, however, without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values serve as the values for your error.

Raise is used for generating run-time errors, and can be used instead of the Error statement (Error still works the same in existing code, and may be appropriate in new code).  Raise is useful for generating errors when writing OLE Automation objects, since the Err object gives the programmer and user richer information than is possible if you generate errors with the Error statement.  For example, with the Raise method the original generator of the error can be specified in the Source property, online Help for the error can be referenced, and so forth.


Applies To

Err Object


 See Also

Clear Method

Description Property

Error Statement

HelpContext Property

HelpFile Property

Number Property

Source Property


Error Function

See Also	Example

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

Syntax

Error[(errornumber)]

The errornumber argument can be any valid error number.  If errornumber is a valid error number, but is not defined, Error returns the string "Application-defined or object-defined error."  If errornumber is not valid, an error occurs.  If errornumber is omitted, the message corresponding to the most recent run-time error is returned.  If no run-time error has occurred, or errornumber is 0, Error returns a zero-length string ("").

Remarks

Examine the property settings of the Err object to identify the most recent run-time error.  The return value of the Error function corresponds to the Description property of the Err object.


 See Also

Err Object

Error Object, Errors Collection

Returning Strings From Functions

Trappable Errors


Error Statement

See Also	Example

Simulates the occurrence of an error.

Syntax

Error errornumber

The errornumber can be any valid error number.

Remarks

The Error statement is supported for backward compatibility.  In new code, especially when creating OLE Automation objects, apply the Raise method to the Err object to generate run-time errors.

If errornumber is defined, the Error statement calls the error handler after filling the Err object's properties with default values (as shown in the following table):

Property	Value

Number	Value specified as argument to Error statement. Can be any valid error number.

Source	Name of the current Visual Basic project.

Description	A string expression corresponding to the return value of the Error function for the specified Number, if this string exists.  If the string doesn't exist, Description contains a zero-length string ("").

HelpFile	The fully qualified drive, path, and filename of the Visual Basic Help file.

HelpContext	The Visual Basic Help file context ID for the error corresponding to the Number property.

If no error handler exists or if none is enabled, an error message is created and displayed from the Err object properties.


 See Also

Clear Method

Err Object

Error Function

On Error Statement

Resume Statement

Raise Method

Trappable Errors


On Error Statement

See Also	Example

Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine.

Syntax

On Error GoTo line

On Error Resume Next

On Error GoTo 0

The On Error statement syntax can have any of the following forms:

Statement	Description

On Error GoTo line 	Enables the error-handling routine that starts at line, which is any line label or line number.  Thereafter, if a run-time error occurs, control branches to line, making the error handler active.  The specified line must be in the same procedure as the On Error statement; otherwise, a compile-time error occurs.

On Error Resume Next	Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred; that is, execution continues.  It's recommended to use this form rather than On Error GoTo when accessing objects.

On Error GoTo 0	Disables any enabled error handler in the current procedure.

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, an error message is displayed and execution stops.

An "enabled" error handler is one that has been turned on by an On Error statement; an "active" error handler is an enabled handler that is in the process of handling an error.  If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error.  Control returns to the calling procedure; if the calling procedure has an enabled error handler, it is activated to handle the error.  If the calling procedure's error handler is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found.  If no inactive, enabled 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, execution resumes in the current procedure at the point designated by the Resume statement.

Note   An error-handling routine is not a Sub or Function procedure.  It is a section of code marked by a line label or line number.

Error-handling routines rely on the value in the Err object's Number property to determine the cause of the error.  The error-handling routine should test or save relevant Err object property  values before any other error can occur or before a procedure that could cause an error is called.  The values in the Err object's properties reflect only the most recent error.  The error message associated with Err.Number is contained in Err.Description.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. .  This allows execution to continue despite a run-time error.  You can then build the error-handling routine inline within the procedure, rather than transfer control to another location within the procedure.  An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine.

Note   The On Error Resume Next construct may be preferable to On Error GoTo when dealing with errors generated during access to other objects, since it permits unambiguous identification of the object whose error code is being returned.  Checking Err after each interaction with an object removes ambiguity about which object your code was accessing when the error occurred because the context is immediate.  Thus, you can be sure of which object placed the error code in Err.Number, as well as which object originally generated the error (the one specified in Err.Source).

On Error GoTo 0 disables error handling in the current procedure.  It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0.  Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement, as appropriate, immediately before 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 separate it from the normal procedure flow.  This is only one possible solution [image] error-handling code can be placed anywhere in a procedure.

Untrapped errors in OLE Automation objects are returned to the controlling application when the OLE Automation object is running as an executable file.  Within the development environment, they are only returned to the OLE Automation controller if the Break In OLE Server option (on the Advanced tab in the Options dialog box from the Tools menu) is set to False.

When writing an OLE Automation object, if your object accesses other objects, you should try to handle errors passed back from them unhandled.  If you cannot handle such errors, your object should pass them back to the caller of your object, but should first map the error code in Err.Number to one of your own errors.  You should specify your error by adding your error code to the constant vbObjectError.  For example, if your error code is 1052, assign it as follows:

Err.Number = vbObjectError + 1052

Note   On 32-bit Microsoft Windows operating systems, system errors during calls to dynamic-link libraries (DLL), don't raise exceptions and can't be trapped with Visual Basic error trapping.  When calling DLL functions, you should check each return value for success or failure (according to the API specifications), and in the event of a failure, check the value in the Err object's LastDLLError property.


 See Also

End Statement

Err Object

Exit Statement

Resume Statement

Trappable Errors


Resume Statement

See Also	Example

Resumes execution after an error-handling routine is finished.

Syntax

Resume [0]

Resume Next

Resume line

The Resume statement syntax can have any of the following forms:

Statement	Description

Resume [0]	If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused the error.  If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.

Resume Next	If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error.  If the error occurred in a called procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine (or On Error Resume Next statement).

Resume line	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.

Remarks

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 a procedure (an End Sub, End Function, or End Property statement) is encountered before a Resume statement is encountered, an error occurs because a logic error is assumed to have been made inadvertently.  However, if an Exit Sub, Exit Function, or Exit Property statement is encountered while an error handler is active, no error occurs because it is considered a deliberate redirection of execution.


See Also

End Statement

Err Object

Exit Statement

On Error Statement

Trappable Errors


LastDLLError Property

See Also	Applies To

Returns a system error code produced by a call into a dynamic-link library (DLL). Occurs only on 32-bit Microsoft Windows operating systems.

Syntax

object.LastDLLError

The object placeholder represents an object expression that evaluates to an object in the Applies To list.

Remarks

The LastDLLError property is relevant only to 32-bit Windows systems.  It applies only to DLL calls that require a Declare statement within the Visual Basic code.  When such a call is made, the called function usually returns a code indicating success or failure, and the LastDLLError property is filled.  Check the documentation for the DLL's functions to determine what return values indicate success or failure.  Whenever the failure code is returned, the Visual Basic application should immediately check the LastDLLError property.  No exception is raised when the LastDLLError property is set.


LastDLLError Property Applies To

Err Object


 See Also

Clear Method

Declare Statement

Description Property

HelpContext Property

HelpFile Property

Number Property

On Error Statement

Raise Method

Source Property


Choose Function

See Also	Example

Selects and returns a value from a list of arguments.

Syntax

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

The Choose function syntax has these parts:

Part	Description

index	Numeric expression or field that results in a value between 1 and the number of available choices.

choice	Variant expression containing one of the possible choices.

Remarks

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

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

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

The Choose function returns a #Null# if index is less than 1 or greater than the number of choices listed.

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


See Also

IIf Function


DateAdd Function

See Also	Example

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

Syntax

DateAdd(interval, number, date)

The DateAdd function syntax has these named arguments:

Part	Description

interval	String expression, as described in Settings, 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.

Settings

The interval argument has these settings:

Setting	Description

yyyy	Year

q	Quarter

m	Month

y	Day of year

d	Day

w	Weekday

ww	Week

h	Hour

n	Minute

s	Second

Remarks

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

If you want to add days to date, you can use Day of Year ("y"), Day ("d"), or Weekday ("w").

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

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

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

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

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


See Also

DateDiff Function

DatePart Function

Day Function

Format Function

Now Function

Weekday Function

Year Function


DateDiff Function

See Also	Example

Returns the number of time intervals between two specified dates.

Syntax

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

The DateDiff function syntax has these named arguments:

Part	Description

interval	String expression, as described in Settings,  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.

firstdayofweek	A constant, as described in Settings, that specifies the first day of the week. If not specified, Sunday is assumed.

firstweekofyear	A constant, as described in Settings, that specifies the first week of the year.  If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

interval	Time interval

yyyy	Year

q	Quarter

m	Month

y	Day of year

d	Day

w	Weekday

ww	Week

h	Hour

n	Minute

s	Second

The firstdayofweek argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use application setting if one exists; otherwise use NLS API setting.

vbSunday	1	Sunday (default)

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday

The firstweekofyear argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use application setting if one exists; otherwise use NLS API setting.

vbFirstJan1	1	Start with week in which January 1 occurs (default).

vbFirstFourDays	2	Start with the first week that has at least four days in the new year.

vbFirstFullWeek	3	Start with first full week of the year.

Remarks

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

If you want to know the number of days between date1 and date2, you can use either Day of Year ("y") or Day ("d").

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

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

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

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


See Also

DateAdd Function

DatePart Function

Day Function

Format Function

Now Function

Weekday Function

Year Function


DatePart Function

See Also	Example

Returns a specified part of a given date.

Syntax

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

The DatePart function syntax has these named arguments:

Part	Description

interval	String expression, as described in Settings, that is the interval of time you want to return.

date	Date that you want to evaluate.

firstdayofweek	A constant, as described in Settings, that specifies the first day of the week. If not specified, Sunday is assumed.

firstweekofyear	A constant, as described in Settings, that specifies the first week of the year.  If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The interval argument has these settings:

Setting	Description

yyyy	Year

q	Quarter

m	Month

y	Day of year

d	Day

w	Weekday

ww	Week

h	Hour

n	Minute

s	Second

The firstdayofweek argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use application setting if one exists; otherwise use NLS API setting.

vbSunday	1	Sunday (default)

vbMonday	2	Monday

vbTuesday	3	Tuesday

vbWednesday	4	Wednesday

vbThursday	5	Thursday

vbFriday	6	Friday

vbSaturday	7	Saturday

The firstweekofyear argument has these settings:

Constant	Value	Description

vbUseSystem	0	Use application setting if one exists; otherwise use NLS API setting.

vbFirstJan1	1	Start with week in which January 1 occurs (default).

vbFirstFourDays	2	Start with the first week that has at least four days in the new year.

vbFirstFullWeek	3	Start with first full week of the year.

Remarks

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

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

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


Environ Function

Example

Returns the string associated with an operating system environment variable.

Syntax

Environ({envstring | number})

The Environ function syntax has these named arguments:

Part	Description

envstring	String expression containing the name of an environment variable.

number	Numeric expression corresponding to the numeric order of the environment string in the environment-string table. The number argument can be any numeric expression, but is rounded to a whole number before it is evaluated.

Remarks

If envstring can't be found in the environment-string table, a zero-length string is returned.  Otherwise, Environ returns the text assigned to the specified envstring; that is, the text following the equal sign in the environment-string table for that environment variable.

If you specify number, the string occupying that numeric position in the environment-string table is returned.  In this case, Environ returns all of the text, including envstring.  If there is no environment string in the specified position, Environ returns a zero-length string ("").


See Also

DateAdd Function

DateDiff Function

Day Function

Format Function

Now Function

Weekday Function

Year Function


IIf Function

See Also	Example

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

Syntax

IIf(expr, truepart, falsepart)

The IIf function syntax has these named arguments:

Part	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.

Remarks

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


See Also

Choose Function

If...Then...Else Statement


Partition Function

Example

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

Syntax

Partition(number, start, stop, interval)

The Partition function syntax has these named arguments:

Part	Description

number	Whole number that you want to evaluate against the ranges.

start	Whole number that is the start of the overall range of numbers.  It can't be less than 0.

stop	Whole number that is the end of the overall range of numbers.  It can't be equal to or less than start.

interval	Whole number that is the interval spanned by each range in the series from start to stop.  It can't be less than 1.

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 within various ranges (for example, order values from 1 to 1000, 1001 to 2000, and so on).

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

start	stop	interval	Before First	First Range	Last Range	After Last
0	99	5	"   :1"	"  0:  4"	" 95: 99"	" 100:   "
20	199	10	"    :  19"	"  20:  29"	" 190: 199"	" 200:    "
100	1010	20	"     :   99"	"  100:  119"	" 1000: 1010"	" 1011:     "
In the table shown above, the third line shows the result when start and stop define a set of numbers that can't be evenly divided by interval. The last range extends to stop (11 numbers) even though interval is 20.

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

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

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


QBColor Function

See Also	Example

Returns the RGB color code corresponding to a color number.

Syntax

QBColor(color)

The color argument is a whole number in the range 0 to 15, as described in Settings.

Settings

The color argument has these settings:

Number	Color	Number	Color
0	Black	8	Gray
1	Blue	9	Light Blue
2	Green	10	Light Green
3	Cyan	11	Light Cyan
4	Red	12	Light Red
5	Magenta	13	Light Magenta
6	Yellow	14	Light Yellow
7	White	15	Bright White
Remarks

The color argument represents color values used by other versions of Basic (such as Microsoft Visual Basic for MS-DOS and the Basic Compiler).  Starting with the least-significant byte, the returned value species the red, green, and blue values used to set the appropriate color in the RGB system used by Visual Basic for applications.


See Also

RGB Function


Switch Function

See Also	Example

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(expr-1, value-1[, expr-2, value-2 . . . [, expr-n, value-n]])

The Switch function syntax has these parts:

Part	Description

expr	Variant expression you want to evaluate.

value	Value or expression that is returned if the corresponding expression is True.

Remarks

The Switch function argument list consists of pairs of expressions and values.  The expressions are evaluated as they appear in the list from left to right and the value associated with the first expression to evaluate True is returned. If the parts aren't properly paired, a run-time error occurs.  For example, if expr-1 is True, Switch returns value-1. If expr-1 is False, but expr-2 is True, Switch returns value-2, and so on.

Switch returns a Null value if:

None of the expressions is True.

The first True expression has a corresponding value that is Null.

Switch evaluates all of the expressions, even though it returns only one of them.  For this reason, you should watch for undesirable side effects.  For example, if the evaluation of any expression results in a division by zero error, an error occurs.


See Also

Choose Function

IIf Function

Select Case Statement


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

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

Syntax

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

The DDB function has these named arguments:

Part	Description

cost	Initial cost of the asset.

salvage	Value of the asset at the end of its useful life.

life	Length of useful life of the asset.

period	Period for which asset depreciation is calculated.

factor	Rate at which the balance declines. If omitted, 2 (double-declining method) is assumed.

Remarks

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

The 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 to calculate depreciation for a given period:

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


See Also

Financial Functions


FV Function

See Also	Example

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

Syntax

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

The FV function has these named arguments:

Part	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. If omitted, 0 is assumed.

type	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

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 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.


See Also

Financial Functions


IPmt Function

See Also	Example

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[, type]])

The IPmt function has these named arguments:

Part	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.  For example, the future value of a loan is $0 because that's it value after the final payment.  However, if you want to save $50,000 for your child's education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.

type	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

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 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.


See Also

Financial Functions


IRR Function

See Also	Example

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

Syntax

IRR(values()[, guess])

The IRR function has these named arguments:

Part	Description

values()	Array of cash flow values.  The array must contain at least one negative value (a payment) and one positive value (a receipt).

guess	Value you estimate will be returned by IRR.  If omitted, guess is 0.1 (10 percent).

Remarks

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

The IRR function uses the order of values within the array to interpret the order of payments and receipts.  Be sure to enter your payment and receipt values in the correct sequence.  The cash flow for each period doesn't have to be 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.


See Also

Financial Functions


MIRR Function

See Also	Example

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

Syntax

MIRR(values(), finance_rate, reinvest_rate)

The MIRR function has these named arguments:

Part	Description

values()	Array of cash flow values.  The array must contain at least one negative value (a payment) and one positive value (a receipt).

finance_rate	Interest rate paid as the cost of financing.

reinvest_rate	Interest rate received on gains from cash reinvestment.

Remarks

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

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

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


See Also

Financial Functions


NPer Function

See Also	Example

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

Syntax

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

The NPer function has these named arguments:

Part	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. For example, the future value of a loan is $0 because that's it value after the final payment.  However, if you want to save $50,000 for your child's education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.

type	Number indicating when payments are due.  Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

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).

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


See Also

Financial Functions


NPV Function

See Also	Example

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, values())

The NPV function has these named arguments:

Part	Description

rate	Discount rate over the length of the period, expressed as a decimal.

values()	Array of cash flow values.  The array must contain at least one negative value (a payment) and one positive value (a receipt).

Remarks

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

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

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

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

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


See Also

Financial Functions


Pmt Function

See Also	Example

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

Syntax

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

The Pmt function has these named arguments:

Part	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. For example, the future value of a loan is $0 because that's it value after the final payment.  However, if you want to save $50,000 for your child's education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.

type	Number indicating when payments are due.  Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

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 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.


See Also

Financial Functions


PPmt Function

See Also	Example

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[, type]])

The PPmt function has these named arguments:

Part	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. For example, the future value of a loan is $0 because that's it value after the final payment.  However, if you want to save $50,000 for your child's education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.

type	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

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 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.


See Also

Financial Functions


PV Function

See Also	Example

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[, type]])

The PV function has these named arguments:

Part	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. For example, the future value of a loan is $0 because that's it value after the final payment.  However, if you want to save $50,000 for your child's education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.

type	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

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 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.


See Also

Financial Functions


Rate Function

See Also	Example

Returns the interest rate per period for an annuity.

Syntax

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

The Rate function has these named arguments:

Part	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. For example, the future value of a loan is $0 because that's it value after the final payment.  However, if you want to save $50,000 for your child's education over 18 years, then $50,000 is the future value. If omitted, 0 is assumed.

type	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

guess	Value you estimate will be returned by Rate. If omitted, guess is 0.1 (10 percent).

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).

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.


See Also

Financial Functions


SLN Function

See Also	Example

Returns the straight-line depreciation of an asset for a single period.

Syntax

SLN(cost, salvage, life)

The SLN function has these named arguments:

Part	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.

Remarks

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.


See Also

Financial Functions


SYD Function

See Also	Example

Returns the sum-of-years' digits depreciation of an asset for a specified period.

Syntax

SYD(cost, salvage, life, per)

The SYD function has these named arguments:

Part	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.

per	Period for which asset depreciation is calculated.

Remarks

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


See Also

Financial Functions


Me

See Also

The Me keyword in Visual Basic behaves like an implicitly declared variable.  It is automatically available to every procedure in a class module.  When a class can have more than one instance, Me provides a way to refer to the specific instance of the class where the code is executing.  Using Me is particularly useful when you want to pass information about the currently executing instance of a class to a procedure in another module.  For example, suppose you have the following procedure in a module:

Sub ChangeFormColor(FormName As Form)

FormName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)

End Sub

You can call this procedure and pass the current instance of the Form class as an argument using the following statement in one of the procedures in your form code:

ChangeFormColor Me


See Also

Set Statement


New

The New keyword is used in these contexts:

Dim Statement

Private Statement

Public Statement

Set Statement

Static Statement


Nothing

See Also

The Nothing keyword in Visual Basic is used to disassociate an object variable from any actual object.  Use the Set statement to assign Nothing to an object variable.  For example:

Set MyObject = Nothing

Several object variables can refer to the same actual object.  When Nothing is assigned to an object variable, that variable no longer refers to any actual object.  When several object variables refer to the same object, memory and system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly using Set, or implicitly after the last object variable set to Nothing goes out of scope.


See Also

Dim Statement

Private Statement

Public Statement

Set Statement

Static Statement


Add Method (Collection Object)
Add Method

See Also	Example	Applies To

Adds a member to a Collection object.

Syntax

object.Add(item, key, before, after)

The Add method syntax has the following object qualifier and named-arguments:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

item	Required.  An expression of any type that specifies the member to add to the collection.

key	Optional.  A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection.

before	Optional.  An expression that specifies a relative position in the collection.  The member to be added is placed in the collection before the member identified by the before argument.  If a numeric expression, before must be a number from 1 to the value of the collection's Count property.  If a string expression, before must correspond to the key specified when the member being referred to was added to the collection.  You can specify before or after positions but not both.

after	Optional.  An expression that specifies a relative position in the collection.  The member to be added is placed in the collection after the member identified by the after argument.  If numeric, after must be a number from 1 to the value of the collection's Count property.  If a string, after must correspond to the key specified when the member being referred to was added to the collection.  You can specify before or after positions but not both.

Remarks

An error occurs if a value provided for before or after would not return a member of the collection when provided to the Item method as the index.  In other words, whether the before or after argument is a string or numeric expression, it must refer to an existing member of the collection.

An error also occurs if a specified key duplicates the key for an existing member of the collection.


See Also

Item Method

Remove Method


Add Method Applies To

Collection Object


Item Method

See Also	Example	Applies To

Returns a specific member of a collection, either by position or by key.

Syntax

object.Item(index)

The Item method syntax has the following object qualifier and part:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

index	Required.  An expression that specifies the position of a member of the collection.  If a numeric expression, index must be a number from 1 to the value of the collection's Count property.  If a string expression, index must correspond to the key specified when the member being referred to was added to the collection.

Remarks

If the value provided as index does not match any existing member of the collection, an error occurs.

The Item method is the default method for a collection.  Therefore, the following lines of code are equivalent:

Print MyCollection(1)

Print MyCollection.Item(1)


See Also

Add Method

Remove Method


Item Method Applies To

Collection Object

Columns Collection

Form Collection


Print Method

See Also	Example	Applies To

Debug object [image] Prints text in the Immediate pane of the Debug window.

Form object [image] Prints text on a form.

PictureBox control [image] Prints text in a picture box.

Printer object [image] Prints text on the object.

Syntax

object.Print outputlist

The Print method syntax has the following object qualifier and part:

Part	Description

object	Optional.  An object expression that evaluates to an object in the Applies To list.

outputlist	Optional.  Expression or list of expressions to print.  If omitted, a blank line is printed.

The outputlist argument has the following syntax and parts:

{Spc(n) | Tab(n)} expression charpos

Part	Description

Spc(n)	Optional.  Used to insert space characters in the output, where n is the number of space characters to insert.

Tab(n)	Optional.  Used to position the insertion point at an absolute column number where n is the column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.

expression	Optional.  Numeric or string expressions to print.

charpos	Optional.  Specifies the insertion point for the next character.  Use a semicolon to position the insertion point immediately following the last character displayed.  Use Tab(n) to position the insertion point at an absolute column number.  Use Tab with no argument to position the insertion point at the beginning of the next print zone.  If charpos is omitted, the next character is printed on the next line.

Remarks

Multiple expressions can be separated with either a space or a semicolon.  A space has the same effect as a semicolon.

For the Debug object, all data printed to the Immediate pane is internationally aware; that is, the data is properly formatted (using the appropriate decimal separator).

When you use the Print method with the Printer object, graphical images are clipped at the bottom of the page and text is carried over to the next page.

For Boolean data, either True or False is printed.

Date data is written using the standard short date format recognized by your system.  When either the date or the time component is missing or zero, only the data provided is written.

Nothing is written if outputlist data is Empty.  However, if outputlist data is Null, Null is output.

For error data, the output is written as Error errorcode.

Note   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

Print # Statement

Spc Function

Tab Function


Print Method Applies To

Debug Object

Form Object

PictureBox Control

Printer Object


Remove Method (Collection Object)
Remove Method

See Also	Example	Applies To

Removes a member from a Collection object.

Syntax

object.Remove index

The Remove method syntax has the following object qualifier and part:

Part	Description

object	Required.  An object expression that evaluates to an object in the Applies To list.

index	Required.  An expression that specifies the position of a member of the collection.  If a numeric expression, index must be a number from 1 to the value of the collection's Count property.  If a string expression, index must correspond to the key specified when the member being referred to was added to the collection.

Remarks

If the value provided as index does not match any existing member of the collection, an error occurs.


See Also

Add Method


Remove Method Applies To

Collection Object


Collection Object

See Also	Example	Properties	Methods

A Collection object is an ordered set of items that can be referred to as a unit.

Syntax

Collection

Remarks

The Collection object provides a convenient way to refer to a related group of items as a single object.  The items in a Collection, known as members, need only be related by the fact that they are in the Collection.  It is not necessary that members of a Collection be of the same data type.

A Collection can be created in the same way as other objects.  For example:

Dim X As New Collection

Once created, members can be added to the Collection using the Add method and removed using the Remove method.  Specific members can be returned from the Collection using the Item method, while the entire collection can be iterated using the For Each ... Next statement.


See Also

Add Method

For Each ... Next Statement

Item Method

Remove Method


Collection Object Properties

Count


Collection Object Methods

Add

Item

Remove


Debug Object

Methods

The Debug object sends output to the Debug window at run time.

Syntax

Debug


Debug Object Methods

Print


#Const Directive

See Also	Example

Used to define conditional compiler constants for Visual Basic.

Syntax

#Const constname  = expression

The #Const compiler directive syntax has these parts:

Part	Description

constname	Name of the constant; follows standard variable naming conventions.

expression	Literal, other conditional compiler constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Conditional compiler constants are always Private to the module in which they appear.  It is not possible to create Public compiler constants using the #Const directive.  Public compiler constants can only be created in the user interface.

Only conditional compiler constants (and literals) can be used in expression.  Using a standard constant (a constant defined with Const) or using a constant that is undefined causes an error to occur.  Conversely, constants defined using the #Const keyword can't be used for anything but conditional compilation.

Conditional compiler constants are always evaluated at the module level, regardless of their placement in code.


See Also

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

Compiler Constants

Const Statement


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

See Also	Example

Conditionally compiles selected blocks of Visual Basic code.

Syntax

#If expression Then

statements

[#ElseIf expression-n Then

[elseifstatements]]

[#Else

[elsestatements]]

#End If

The #If...Then...#Else directive syntax has these parts:

Part	Description

expression	Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False.

statements	Visual Basic program lines or compiler directives that are evaluated if the associated expression is True.

expression-n	Same as expression.

elseifstatements 	One or more program lines or compiler directives that are evaluated if expression-n is True.

elsestatements	One or more program lines or compiler directives that are evaluated if no previous expression or expression-n is True.

Remarks

The behavior of the #If...Then...#Else directive is the same as the If...Then...Else statement, except that there is no single-line form of the #If, #Else, #ElseIf, and #End If directives, that is, no other code can appear on the same line as any of the directives. Conditional compilation is typically used to compile the same program for different platforms.  It can also be used to prevent debugging code from appearing in an executable file.  Code excluded during conditional compilation is completely omitted from the final executable file, so it has no size or performance effect.

Regardless of outcome of any evaluation, all expressions are evaluated.  Therefore, all constants used in expressions must be defined [image] any undefined constant evaluates as Empty.

Note   The Option Compare statement doesn't affect expressions in #If and #ElseIf statements.  Expressions in a conditional-compiler directive are always evaluated with Option Compare Text.


See Also

#Const Directive

Compiler Constants

If...Then...Else Statement


DeleteSetting Statement

See Also	Example

Deletes a section or key setting from the Windows registry entry.

Syntax

DeleteSetting(appname, section[, key])

The DeleteSetting statement syntax has these named arguments:

Part	Description

appname	String expression containing the name of the application or project to which the section or key setting applies.

section	String expression containing the name of the section where the key setting is being deleted.  If only appname and section are provided, the specified section is deleted along with all related key settings.

key	String expression containing the name of the key setting being deleted.

Remarks

If all arguments are provided, the specified key setting is deleted.  However, the DeleteSetting statement does nothing if the specified section or key setting does not exist.


See Also

GetAllSettings Function

GetSetting Function

SaveSetting Statement


DeleteSetting Statement Example

The following example first uses the SaveSetting statement to make entries in the Windows registry (or .INI file on 16-bit Windows platforms) for the MyApp application, then uses the DeleteSetting statement to remove them.  Because no key is specified, the whole section is deleted, including the section name and all its keys.

' Place some settings in the registry.

SaveSetting(appname := "MyApp", section := "Startup", _

            key := "Top", setting := 75)

SaveSetting("MyApp","Startup", "Left", 50)

' Remove section and all its settings from registry.

DeleteSetting("MyApp", "Startup")


GetAllSettings Function

See Also	Example

Returns a list of key settings and their respective values from an application's Windows registry entry.

Syntax

GetAllSettings(appname, section)

The GetAllSettings function syntax has these named arguments:

Part	Description

appname	String expression containing the name of the application or project whose key settings are requested.

section	String expression containing the name of the section whose key settings are requested.  GetAllSettings returns a Variant whose contents is a two-dimensional array of strings containing all the key settings in the specified section and their corresponding values.

Remarks

GetAllSettings returns an uninitialized Variant if either appname or section do not exist.


See Also

DeleteSetting Statement

GetSetting Function

SaveSetting Statement


GetAllSettings Function Example

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

' Variant to hold 2-dimensional array returned by GetAllSettings.

Dim MySettings As Variant

' Place some settings in the registry.

SaveSetting(appname := "MyApp", section := "Startup", _

            key := "Top", setting := 75)

SaveSetting("MyApp","Startup", "Left", 50)

' Retrieve the settings.

MySettings = GetAllSettings(appname := "MyApp", section := "Startup")

For Settings = LBound(MySettings, 1) To UBound(MySettings, 1)

Debug.Print MySettings(Settings, 0), MySettings(Settings, 1)

Next Settings

DeleteSetting("MyApp", "Startup")


GetSettings Function
GetSetting Function

See Also	Example

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

Syntax

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

The GetSetting function syntax has these named arguments:

Part	Description

appname	String expression containing the name of the application or project whose key setting is requested.

section	String expression containing the name of the section where the key setting is found.

key	String expression containing the name of the key setting to return.

default	Expression containing the value to return if no value is set in the key setting.  If omitted, default is assumed to be a zero-length string ("").

Remarks

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


See Also

DeleteSetting Statement

GetAllSettings Function

SaveSetting Statement


GetSetting Function Example

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

' Variant to hold 2-dimensional array returned by GetAllSettings.

Dim MySettings As Variant

' Place some settings in the registry.

SaveSetting("MyApp","Startup", "Top", 75)

SaveSetting("MyApp","Startup", "Left", 50)

Debug.Print GetSetting(appname := "MyApp", section := "Startup", _

                       key := "Left", default := "25")

DeleteSetting("MyApp", "Startup")


SaveSetting Statement

See Also	Example

Saves or creates an application entry in the Windows registry entry.

Syntax

SaveSetting(appname, section, key, setting)

The SaveSetting statement syntax has these named arguments:

Part	Description

appname	String expression containing the name of the application or project to which the setting applies.

section	String expression containing the name of the section where the key setting is being saved.

key	String expression containing the name of the key setting being saved.

setting	Expression containing the value that key is being set to.

Remarks

An error occurs if the key setting could not be saved for any reason.


See Also

DeleteSetting Statement

GetAllSettings Function

GetSetting Function


SaveSetting Statement Example

The following example first uses the SaveSetting statement to make entries in the Windows registry (or .INI file on 16-bit Windows platforms) for the MyApp application, then uses the DeleteSetting statement to remove them.

' Place some settings in the registry.

SaveSetting(appname := "MyApp", section := "Startup", _

            key := "Top", setting := 75)

SaveSetting("MyApp","Startup", "Left", 50)

SaveSetting("MyApp","Startup", "Password", "Swordfish")

' Remove app entry and all settings from registry.

DeleteSetting("MyApp", "Startup")


Circle Method Example

This example uses the Circle method to draw a number of concentric circles in the center of a form.  To try this example, paste the code into the General section of a form.  Then press F5 and click the form.

Private 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


Command Function Example

This example uses the Command function to display the command line arguments.

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.


Line Method Example

This example uses the Line method to draw concentric boxes on a form.  To try this example, paste the code into the General section of a form.  Then press F5 and click the form.

Private 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


PSet Method Example

This example uses the PSet method to draw confetti on a form.  To try this example, paste the code into the General section of a form.  Then press F5 and click the form.

Private 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 to other

Loop	' processing.

End Sub


Raise Method Example

This example uses the Err object's Raise method to generate an error within an OLE Automation object written in Visual Basic.  It has the programmatic ID MyProj.MyObject.

Const MyContextID = 1010407	' Define a constant for contextID.

Function TestName(CurrentName, NewName)

If Instr(NewName, "bob") Then	' Test the validity of NewName.

' Raise the exception

Err.Raise vbObjectError + 27, "MyProj.MyObject", _

"No ""bob"" allowed in your name", "c:\MyProj\MyHelp.Hlp", _

MyContextID

End If

End Function


Clear Method Example

This example uses the Err object's Clear method to reset the numeric properties of the Err object to zero and its string properties to zero-length strings.  If Clear were omitted from the following code, the error message dialog box would be displayed on every iteration of the loop (after an error occurs) whether or not a successive calculation generated an error.

Dim Result(10) As Integer	' Declare array whose elements

' will overflow easily.

On Error Resume Next	' Defer error trapping.

Do Until indx = 10

' Generate an occasional error or store result if no error.

Result(indx) = Rnd * indx * 20000

If Err.Number <> 0 Then

MsgBox Err, , "Error Generated: ", Err.HelpFile, Err.HelpContext

Err.Clear	' Clear Err object properties.

Else

indx = indx + 1

End If

Loop


Err Object Example

This example uses the properties of the Err object in constructing an error-message dialog box.  Note that when you generate a Visual Basic error with the Raise method, if you use the Clear method first, Visual Basic's default values become the properties of the Err object.

' If an error occurs, construct an error message

On Error Resume Next	' Defer error handling.

Err.Clear

Err.Raise 6	' Generate an "Overflow" error.

' Check for error, then show message.

If Err.Number <> 0 Then

Msg = "Error # " & Str(Err.Number) & " was generated by " _

& Err.Source & Chr(13) & Err.Description

MsgBox Msg, , "Error", Err.Helpfile, Err.HelpContext

End If


HelpFile Property Example

This example uses the HelpFile property of the Err object to start Help system.  By default the HelpFile property contains the name of the Visual Basic Help file.

Err.Clear

On Error Resume Next	' Suppress errors for demonstration purposes.

Err.Raise 6	' Generate "Overflow" error.

Msg = "Press F1 or Help to see " & Err.HelpFile & _

" topic for this error"

MsgBox Msg, , "Error: " & Err.Description,Err.HelpFile, Err.HelpContext


HelpContext Property Example

This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the error Overflow.

Err.Clear

On Error Resume Next

Err.Raise 6 ' Generate "Overflow" error.

If Err.Number <> 0 Then

Msg = "Press F1 or Help to see " & Err.HelpFile & " topic for" & _

" the following HelpContext: " & Err.HelpContext

MsgBox Msg, , "Error: " & Err.Description, Err.HelpFile, _

Err.HelpContext

End If


Number Property Example

This example examines the Number property of the Err object to determine whether an error returned by an object was defined by the object, or whether it was mapped to an error defined by Visual Basic.  Note that the constant vbObjectError is a very large negative number that an object adds to its own error code to indicate that the error is defined by the server.  Therefore, subtracting it from Err.Number strips it out of the result.  If the error is object-defined, the base number is left in MyError, which is displayed in a message box along with the original source of the error.  If Err.Number represents a Visual Basic error, then the Visual Basic error number is displayed in the message box.

' First, strip off the constant added by the object to indicate one

' of its own errors.

MyError = Err.Number - vbObjectError

' If you subtract the vbObjectError constant, and the number is still

' in the range 0-65,535, it is an object-defined error code.

If MyError > 0 And MyError < 65535 Then

Msg = "The object you accessed assigned this number to the error: " _

 	& MyError & ". The originator of the error was: " _

& Err.Source & ". Press F1 to see originator's Help topic."

' Otherwise it is a Visual Basic error number.

Else

Msg = "This error (# " & Err.Number & ") is a Visual Basic error" & _

" number. Press Help button or F1 for the Visual Basic Help" _

& " topic for this error."

End If

MsgBox Msg, , "Object Error", Err.HelpFile, Err.HelpContext


Description Property Example

This example assigns a user-defined message to the Description property of the Err object.

Err.Description = "It was not possible to access an object necessary " _

& "for this operation."


Source Property Example

This example assigns the Programmatic ID of an OLE Automation object created in Visual Basic to the variable MyObjectID, then assigns that to the Source property of the Err object when it generates an error with the Raise method.  When handling errors, you should not use the Source property (or any Err properties other than Number) programatically.  The only valid use of properties other than Number is for displaying rich information to an end user in cases where you cannot handle an error.

' An object of type MyClass generates an error and fills all Err object

' properties, including Source, which receives MyObjectID, which is a

' combination of the Title property of the App object and the Name

' property of the MyClass object.

MyObjectID = App.Title & "." & MyClass.Name

Err.Raise	Number := vbObjectError + 894, Source := MyObjectID, _

Description := "Was not able to complete your task", _

HelpFile := MyHelpFile, HelpContext := MyHelpContext


Error Function Example

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

For ErrorNumber = 61 To 64	' Loop through values 61 - 64.

Debug.Print Error(ErrorNumber)	' Print error to Debug window.

Next ErrorNumber


Error Statement Example

This example uses the Error statement to simulate error number 11.

On Error Resume Next	' Defer error handling.

Error 11	' Simulate the "Division by zero" error.


On Error Statement Example

This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure.  In the example, an attempt to delete an open file generates error number 55.  The error is handled in the error-handling routine and control is then returned to the statement that caused it.  The On Error GoTo 0  statement turns off error trapping.  Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain.  Note that Err.Clear is used to clear the Err object's properties after the error is handled.

Sub OnErrorStatementDemo()

On Error GoTo ErrorHandler	' Enable error-handling routine.

Open "TESTFILE" For Output As #1	' Open file for output.

Kill "TESTFILE"	' Attempt to delete open

' file.

On Error Goto 0	' Turn off error trapping.

On Error Resume Next	' Defer error trapping.

ObjectRef = GetObject("MyWord.Basic")	' Try to start nonexistent

' object, then test for

If Err.Number = 440 Then	' OLE Automation error.

' Tell user what happened. Then clear the Err object.

Msg = "There was an error attempting to open the OLE object!"

MsgBox Msg, , "Deferred Error Test"

Err.Clear	' Clear Err object fields

End If

Exit Sub	' Exit to avoid handler.

ErrorHandler:	' Error-handling routine.

Select Case Err.Number	' Evaluate error number.

Case 55	' "File already open" error.

Close #1	' Close open file.

Case Else

' Handle other situations here...

End Select

Resume	' Resume execution at same line

' that caused the error.

End Sub


Resume Statement Example

This example uses the Resume statement to end error handling in a procedure and resume execution with the statement that caused the error.  Error number 55 is generated to illustrate using the Resume statement.

Sub ResumeStatementDemo()

On Error GoTo ErrorHandler	' Enable error-handling routine.

Open "TESTFILE" For Output As #1	' Open file for output.

Kill "TESTFILE"	' Attempt to delete open file.

Exit Sub	' Exit Sub to avoid error handler.

ErrorHandler:	' Error-handling routine.

Select Case Err.Number	' Evaluate error number.

Case 55	' "File already open" error.

Close #1	' Close open file.

Case Else

' Handle other situations here....

End Select

Resume	' Resume execution at same line

' that caused the error.

End Sub


Choose Function Example

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

Function  GetChoice(Ind As Integer)

GetChoice =  Choose(Ind, "Speedy", "United", "Federal")

End Function


DateAdd Function Example

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

Dim FirstDate As Date	' Declare variables.

Dim IntervalType As String

Dim Number As Integer

Dim Msg

IntervalType = "m"	' "m" specifies months as interval.

FirstDate = InputBox("Enter a date")

Number = InputBox("Enter number of months to add")

Msg = "New date: " & DateAdd(IntervalType, Number, FirstDate)

MsgBox Msg


DateDiff Function Example

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

Dim TheDate As Date	' Declare variables.

Dim Msg

TheDate = InputBox("Enter a date")

Msg = "Days from today: " & DateDiff("d", Now, TheDate)

MsgBox Msg


DatePart Function Example

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

Dim TheDate As Date	' Declare variables.

Dim Msg

TheDate = InputBox("Enter a date:")

Msg = "Quarter: " & DatePart("q", TheDate)

MsgBox Msg


Environ Function Example

This example uses the Environ function to supply the entry number and length of the PATH statement from the environment-string table.

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,

End If	' so increment.

Loop Until EnvString = ""

If PathLen > 0 Then

MsgBox Msg	' Display message.

Else

MsgBox "No PATH environment variable exists."

End If


IIf Function Example

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

Function CheckIt (TestMe As Integer)

CheckIt = IIf(TestMe > 1000, "Large", "Small")

End Function


Partition Function Example

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

SELECT DISTINCTROW Partition([freight],0, 500, 50) AS Range,

Count(Orders.Freight) AS Count

FROM Orders

GROUP BY Partition([freight],0,500,50);


QBColor Function Example

This example uses the QBColor function to change the BackColor property of the form passed in as MyForm to the color indicated by ColorCode.  QBColor accepts integer values between 0 and 15.

Sub ChangeBackColor (ColorCode As Integer, MyForm As Form)

MyForm.BackColor = QBColor(ColorCode)

End Sub


Switch Function Example

This example uses the Switch function to return the name of a language that matches the name of a city.

Function MatchUp (CityName As String)

Matchup = Switch(CityName = "London", "English", CityName _

= "Rome", "Italian", CityName = "Paris", "French")

End Function


DDB Function Example

Using the double-declining balance method, this example uses the DDB function to return the depreciation of an asset for a specified period given the initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), the total life of the asset in years (LifeTime), and the period 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 Example

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

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.

Fmt = "###,###,##0.00"	' Define money format.

Payment = InputBox("How much do you plan to save each month?")

APR = InputBox("Enter the expected interest annual percentage rate.")

If APR > 1 Then APR = APR / 100	' Ensure proper form.

TotPmts = InputBox("For how many months do you expect to save?")

PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)

If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD

PVal = InputBox("How much is in this savings account now?")

FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType)

MsgBox "Your savings will be worth " & Format(FVal, Fmt) & "."


IPmt Function Example

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

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.

FVal = 0	' Usually 0 for a loan.

Fmt = "###,###,##0.00"	' Define money format.

PVal = InputBox("How much do you want to borrow?")

APR = InputBox("What is the annual percentage rate of your loan?")

If APR > 1 Then APR = APR / 100	' Ensure proper form.

TotPmts = InputBox("How many monthly payments?")

PayType = MsgBox("Do you make payments at end of the month?", vbYesNo)

If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD

For Period = 1 To TotPmts	' Total all interest.

IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)

TotInt = TotInt + IntPmt

Next Period

Msg = "You'll pay a total of " & Format(TotInt, Fmt)

Msg = Msg & " in interest for this loan."

MsgBox Msg	' Display results.


IRR Function Example

In this example, the IRR function 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 percent.

Fmt = "#0.00"	' Define percentage format.

Values(0) = -70000	' Business start-up costs.

' Positive cash flows reflecting income for four successive years.

Values(1) = 22000 : Values(2) = 25000

Values(3) = 28000 : Values(4) = 31000

RetRate = IRR(Values(), Guess) * 100	' Calculate internal rate.

Msg = "The internal rate of return for these five cash flows is "

Msg = Msg & Format(RetRate, Fmt) & " percent."

MsgBox Msg	' Display internal return rate.


MIRR Function Example

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

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 Example

This example uses the NPer function to return 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.

FVal = 0	' Usually 0 for a loan.

PVal = InputBox("How much do you want to borrow?")

APR = InputBox("What is the annual percentage rate of your loan?")

If APR > 1 Then APR = APR / 100	' Ensure proper form.

Payment = InputBox("How much do you want to pay each month?")

PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)

If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD

TotPmts = NPer(APR / 12, -Payment, PVal, FVal, PayType)

If Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1

MsgBox "It will take you " & TotPmts & " months to pay off your loan."


NPV Function Example

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

Static Values(5) As Double	' Set up array.

Fmt = "###,##0.00"	' Define money format.

Guess = .1	' Guess starts at 10 percent.

RetRate = .0625	' Set fixed internal rate.

Values(0) = -70000	' Business start-up costs.

' Positive cash flows reflecting income for four successive years.

Values(1) = 22000 : Values(2) = 25000

Values(3) = 28000 : Values(4) = 31000

NetPVal = NPV(RetRate, Values())	' Calculate net present value.

Msg = "The net present value of these cash flows is "

Msg = Msg & Format(NetPVal, Fmt) & "."

MsgBox Msg	' Display net present value.


Pmt Function Example

This example uses the Pmt function to return 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.

Fmt = "###,###,##0.00"	' Define money format.

FVal = 0	' Usually 0 for a loan.

PVal = InputBox("How much do you want to borrow?")

APR = InputBox("What is the annual percentage rate of your loan?")

If APR > 1 Then APR = APR / 100	' Ensure proper form.

TotPmts = InputBox("How many monthly payments will you make?")

PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)

If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD

Payment = Pmt(APR / 12, TotPmts, -PVal, FVal, PayType)

MsgBox "Your payment will be " & Format(Payment, Fmt) & " per month."


PPmt Function Example

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

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.

NL = Chr(13) & Chr(10)	' Define newline.

TB = Chr(9)	' Define tab.

Fmt = "###,###,##0.00"	' Define money format.

FVal = 0	' Usually 0 for a loan.

PVal = InputBox("How much do you want to borrow?")

APR = InputBox("What is the annual percentage rate of your loan?")

If APR > 1 Then APR = APR / 100	' Ensure proper form.

TotPmts = InputBox("How many monthly payments do you have to make?")

PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)

If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD

Payment = Abs(-Pmt(APR / 12, TotPmts, PVal, FVal, PayType))

Msg = "Your monthly payment is " & Format(Payment, Fmt) & ". "

Msg = Msg & "Would you like a breakdown of your principal and "

Msg = Msg & "interest per period?"

MakeChart = MsgBox(Msg, vbYesNo)	' See if chart is desired.

If MakeChart <> vbNo Then

If TotPmts > 12 Then MsgBox "Only first year will be shown."

Msg = "Month  Payment  Principal  Interest" & NL

For Period = 1 To TotPmts

If Period > 12 Then Exit For	' Show only first 12.

P = PPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)

P = (Int((P + .005) * 100) / 100)	' Round principal.

I = Payment - P

I = (Int((I + .005) * 100) / 100)	' Round interest.

Msg = Msg & Period & TB & Format(Payment, Fmt)

Msg = Msg & TB & Format(P, Fmt) & TB & Format(I, Fmt) & NL

Next Period

MsgBox Msg	' Display amortization table.

End If


PV Function Example

In this example, the PV function returns the present value of an $1,000,000 annuity that will provide $50,000 a year for the next 20 years.  Provided are the expected annual percentage rate (APR), the total number of payments (TotPmts), the amount of each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether each payment is made at the beginning or end of the payment period (PayType).  Note that 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 Example

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

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.

Fmt = "##0.00"	' Define percentage format.

FVal = 0	' Usually 0 for a loan.

Guess = .1	' Guess of 10 percent.

PVal = InputBox("How much did you borrow?")

Payment = InputBox("What's your monthly payment?")

TotPmts = InputBox("How many monthly payments do you have to make?")

PayType = MsgBox("Do you make payments at the end of the month?", _

vbYesNo)

If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD

APR = (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100

MsgBox "Your interest rate is " & Format(CInt(APR), Fmt) & " percent."


SLN Function Example

This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).

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 Example

Using the sum-of-years' digits method, this example illustrates the use of the SYD function to return the depreciation of an asset for a specified period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).  The period for which the depreciation is calculated is 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) & "."


Add Method Example

This example uses the Add method to add Inst objects (instances of a class called Class1 containing a Public variable InstanceName) to a collection called MyClasses.  To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 ( type Public InstanceName) to hold the names of each instance.  Leave the default name as Class1.  Copy and paste the following code into the Form_Load event procedure.

Private Sub Form_Load()

Dim MyClasses As New Collection	' Create a Collection object.

Dim Num As Integer	' Counter for individualizing keys.

Dim Msg As String	' Variable to hold prompt string.

Dim TheName, MyObject, NameList	' Variants to hold information.

Do

Dim Inst As New Class1	' Create a new instance of Class1.

Num = Num + 1	' Increment Num, then get a name.

Msg = "Please enter a name for this object." & Chr(13) _

 & "Press Cancel to see names in collection."

TheName = InputBox(Msg, "Name the Collection Items")

Inst.InstanceName = TheName	' Put name in object instance.

' If user entered name, add it to the collection.

If Inst.InstanceName <> "" Then

' Add the named object to the collection.

MyClasses.Add Item := Inst, Key := CStr(Num)

End If

' Clear the current reference in preparation for next one.

Set Inst = Nothing

Loop Until TheName = ""

For Each MyObject In MyClasses	' Create list of names.

NameList = NameList & MyObject.InstanceName & Chr(13)

Next MyObject

' Display the list of names in a message box.

MsgBox NameList, , "Instance Names In MyClasses Collection"

For Num = 1 To MyClasses.Count	' Remove name from collection.

MyClasses.Remove 1	' Since collections are reindexed

Next Num	' automatically, remove the first

' member on each iteration.

End Sub


Print Method Example

Using the Print method, this example displays the value of the variable MyVar in the Immediate pane of the Debug window.  Note that the Print method only applies to objects that can display text.

Dim MyVar

MyVar = "Come see me in the Immediate pane."

Debug.Print MyVar


Remove Method Example

This example illustrates the use of the Remove method to remove objects from a Collection object, MyClasses.  This code removes the object whose index is 1 on each iteration of the loop.

Dim Num

For Num = 1 To MyClasses.Count

MyClasses.Remove 1	' Remove the first object each time

' through the loop until there are

' no objects left in the collection.

Next Num


 Item Method Example

This example uses the Item method to retrieve a reference to an object in a collection.  Assuming Birthdays is a Collection object, the following code retrieves from the collection references to the objects representing Bill Smith's and Adam Smith's birthdays, using the keys "SmithBill" and "SmithAdam" as the index arguments.  Note that the first call explicitly specifies the Item method, but the second does not.  Both calls work because the Item method is the default for a Collection object.  The references, assigned to SmithBillBD and SmithAdamBD (using Set), can be used to access the properties and methods of the specified objects.  To run this code, create the collection and populate it with at least the two referenced members.

Dim SmithBillBD As Object

Dim SmithAdamBD As Object

Set SmithBillBD = Birthdays.Item("SmithBill")

Set SmithAdamBD = Birthdays("SmithAdam")


Collection Object Example

This example creates a Collection object (MyClasses), then creates a dialog box in which users can add objects to the collection.  To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 ( type Public InstanceName) to hold the names of each instance.  Leave the default name as Class1.  Copy and paste the following code into the General section of another module, then start it with the statement ClassNamer in another procedure.

Sub ClassNamer()

Dim MyClasses As New Collection	' Create a Collection object.

Dim Num	' Counter for individualizing keys.

Dim Msg As String	' Variable to hold prompt string.

Dim TheName, MyObject, NameList	' Variants to hold information.

Do

Dim Inst As New Class1	' Create a new instance of Class1.

Num = Num + 1	' Increment Num, then get a name.

Msg = "Please enter a name for this object." & Chr(13) _

 & "Press Cancel to see names in collection."

TheName = InputBox(Msg, "Name the Collection Items")

Inst.InstanceName = TheName	' Put name in object instance.

' If user entered name, add it to the collection.

If Inst.InstanceName <> "" Then

' Add the named object to the collection.

MyClasses.Add item := Inst, key := CStr(Num)

End If

' Clear the current reference in preparation for next one.

Set Inst = Nothing

Loop Until TheName = ""

For Each MyObject In MyClasses	' Create list of names.

NameList = NameList & MyObject.InstanceName & Chr(13)

Next MyObject

' Display the list of names in a message box.

MsgBox NameList, , "Instance Names In MyClasses Collection"

For Num = 1 To MyClasses.Count	' Remove name from the collection.

MyClasses.Remove 1	' Since collections are reindexed

' automatically, remove the first

Next	' member on each iteration.

End Sub


Count Property Example

This example uses the Collection object's Count property to specify how many iterations are required to remove all the elements of the collection called MyClasses.  When collections are numerically indexed, the base is 1 by default.  Since collections are reindexed automatically when a removal is made, the following code removes the first member on each iteration.

Dim Num

For Num = 1 To MyClasses.Count	' Remove name from the collection.

MyClasses.Remove 1	' Default collection numeric indexes

Next	' begin at 1.


CreateObject Function Example

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

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

Set xlApp = CreateObject("excel.application")

xlApp.Visible = True	' You may have to set Visible property to True

' if you want to see the application.

' Use xlApp to access Microsoft Excel's

' other objects.

' ...

xlApp.Quit	' When you finish, use the Quit method to close

Set xlApp = Nothing	' the application, then release the reference.


GetObject Function Example

This example uses the GetObject function to get a reference to a specific Microsoft Excel Worksheet (MyXL).  It uses the worksheet's Application property to make Microsoft Excel visible, to close it, and so on.  The first call to GetObject causes an error if Microsoft Excel is not already running.  In the example, the error causes the ExcelWasNotRunning flag to be set to True.  The second call to GetObject specifies a file to open.  If Microsoft Excel is not already running, this second call starts it, and returns a reference to the worksheet represented by the specified file.  The file, MYTEST.XLS in the example, must exist in the specified location; otherwise the Visual Basic error OLE Automation error is generated.  Next, the example code makes both Microsoft Excel and the window containing the specified worksheet visible.  Finally, if there was no previous version of Microsoft Excel running, the code uses the Application object's Quit method to close Microsoft Excel.  If the application was already running, no attempt is made to close it.  The reference itself is released by setting it to Nothing.

Dim MyXL As Object	' Variable to hold reference

' to Microsoft Excel.

Dim ExcelWasNotRunning As Boolean	' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running.

On Error Resume Next	' Defer error trapping.

' GetObject function called without the first argument returns a

' reference to an instance of the application. If the application isn't

' running, an  error occurs. Note the comma used as the first argument

' placeholder.

Set MyXL = GetObject(, "Excel.Application")

If Err.Number <> 0 Then ExcelWasNotRunning = True

Err.Clear	' Clear Err object in case error occurred.

' Set the object variable to reference the file you want to see.

Set MyXL = GetObject("c:\vb4\MYTEST.XLS")

' Show Microsoft Excel through its Application property. Then

' show the actual window containing the file using the Windows

' collection of the MyXL object reference.

MyXL.Application.Visible = True

MyXL.Parent.Windows(1).Visible = True

' Do manipulations of your

 	' file here.

' ...

' If this copy of Microsoft Excel was not already running when you

' started, close it using the Application property's Quit method.

' Note that when you try to quit Microsoft Excel, the Microsoft Excel

' title bar blinks and Microsoft Excel displays a message asking if you

' want to save any loaded files.

If ExcelWasNotRunning = True Then MyXL.Application.Quit

Set MyXL = Nothing	' Release reference to the

' application and spreadsheet.


#Const Directive Example

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

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


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

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

' If Win16 evaluates as true, do the statements following the #If.

#If Win16 Then

'. Place exclusively 16-bit Windows statements here.

'.

'.

' Otherwise, if it is a 32-bit Windows program, do this:

#ElseIf Win32 Then

'. Place exclusively 32-bit Windows statements here.

'.

'.

' Otherwise, if it is neither, do this:

#Else

'. Place other platform statements here.

'.

'.

#End If


Keyword Not Found

The keyword you've selected can't be found in Visual Basic Help.  You may have misspelled the keyword, selected too much or too little text, or asked for help on a word that is not a valid Visual Basic keyword.

The easiest way to get help on a specific keyword is to position the insertion point anywhere within the keyword you want help on and press F1.  You do not need to select the keyword.  In fact, if you select only a portion of the keyword, or more than a single word, Help will not find what you're looking for.

The Value property topic is displayed when you press F1 with the insertion point between the "a" and the "l" in the Value keyword as shown in the following example.

To use the built-in Help search dialog box, press the Help Topics button on the toolbar.