 Visual Basic Help

Product Support	Glossary

How to use Visual Basic

Introducing and Learning Visual Basic

Building a Visual Basic Application

Creating the Interface

Setting Properties

Writing and Debugging Code

Reference

Properties	Programming Language
Events	Programming Environment
Objects	Trappable Errors


Creating the Interface

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

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

Create a form for each window in your application.

Use the Toolbox to draw the controls for each form.

Create a menu bar for the main form.

More information

Adding and Deleting Controls at Run Time

Adding and Deleting Menu Commands at Run Time

Aligning an Item to the Grid

Assigning an Icon to a Form

Changing Grid Spacing

Creating a Control Array

Creating a Menu Bar

Creating a Menu Control Array

Displaying Graphics on a Form

Displaying or Hiding the Grid

Drawing a Control

Drawing Lines and Shapes on a Form

Selecting Controls


Setting Properties

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

Set form and control properties.

More information

Accessing Screen Properties

Properties List

Setting Colors

Setting Form and Control Properties

Setting Tab Order

Specifying Access Keys

Using MDI Features


Writing Code

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

Write event procedures and general procedures.

Debug your code.

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

More information

Communicating with Other Applications

Controlling Program Flow

Debugging Code

Processing Files

Project Management

Using Language Elements

Using the Code Window


Using the Code Window

Adding, Editing and Deleting Watch Expressions

Executing a Specific Statement

Guidelines for Entering and Editing Code

Importing a Text File into Code

Replacing Text in Code

Saving and Loading forms in ASCII Format

Searching for Text in Code

Setting and Clearing Breakpoints

Splitting a Code Window Into Panes

Turning Syntax Checking On or Off

Using Example Code from Online Help

Using the Debug Window


Using Language Elements

Attaching an Event Procedure to a Form or Control

Creating a General Procedure

Creating Custom Colors

Entering Declarations in Code

Finding a Procedure

Specifying Access Keys


Debugging code

Adding, Editing and Deleting Watch Expressions

Continuing Execution

Debugging Checklist

Executing a Specific Statement

Guidelines for Entering and Editing Code

KnowledgeBase Articles from Microsoft Product Support

Restarting Execution

Setting and Clearing Breakpoints

Starting Execution

Tracing Execution

Turning Syntax Checking On or Off

Using Example Code from Online Help

Using Instant Watch

Using the Debug Window

Using Watch Expressions


Processing Files

Importing a Text File into Code

Saving and Loading Forms in ASCII Format

KnowledgeBase Articles from Microsoft Product Support

Replacing Text in Code

Saving Your Work

Searching for Text in Code


Communicating with other applications

Creating a DDE Source or Destination Link

KnowledgeBase Articles from Microsoft Product Support

Using Dynamic Data Exchange (DDE)

Using Custom Controls


Controlling program flow

Ending Execution

Executing a Specific Statement

Halting Execution

KnowledgeBase Articles from Microsoft Product Support

Restarting Execution

Specifying a Startup Form

Starting Execution


Project management

Importing a Text File into Code

KnowledgeBase Articles from Microsoft Product Support

Saving and Loading Forms in ASCII Format

Saving Your Work

Using Example Code from Online Help


Introducing and Learning Visual Basic

Introducing Visual Basic

Click here to exit Help and run a quick demonstration of Visual Basic features.

Learning Visual Basic

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

How Visual Basic Works

Creating an Application

Writing Event-driven Programs

Working with Forms and Controls

Adding Menus

Debugging Your Application

Using Color and Graphics


Objects

Global Objects

Clipboard Object

Debug Object

Printer Object

Screen Object

App Object

Interface Objects

Controls

Form

MDI Form


Programming Environment

Visual Basic Windows

Code Window

Color Palette

Debug Window

Menu Bar

Menu Design Window

Project Window

Properties Window

Toolbar

Toolbox

Interface Information

Keyboard Guide

Menus & Commands


Glossary


Glossary

A

access key

active window

ANSI Character Set

application

argument

array

ASCII Character Set

assignment statement

automatic formatting

B

binary format

bit field

bit mask

bit

bitmap

bit-wise

Boolean expression

block If

break mode

breakpoint

C

Cancel button

Caption

cascading event

check box

Checked check box

client area

client

Clipboard

collection

combo box

command line

comment

comparison operator

compile time

constant

container

control array

Control-menu box

Control-menu commands

Control Panel

control

cross hair

custom control

D

data type

DDE

declaration

default color box

design time

destination

device context

dialog box

DLL

drag-and-drop operation

E

editing key

Empty

Enabled check box

Enter button

enumerated data type

event procedure

event

executable file

expression

F

focus

form code

form

frame

function key

Function procedure

G

general procedure

graphics method

grid

H

handle

hierarchical menu

horizontal scroll bar

I

icon

image control

index

insertion point

instance

K

keyboard modifier

keyword

L

label

line label

line number

list box

logic error

Long data type

M

Maximize button

MDI child

MDI form

metafile

method

millisecond

Minimize button

modal

modeless

module level

module variable

module

N

navigation key

Null

numeric expression

O

Object box

object data type

object

option button

P

Paste Link command

path

pen

persistent bitmap

picture box

pixel

point

poke

position indicator

Printer object

Proc box

procedure call

procedure level

procedure template

procedure

Project window

project

Property list

Properties window

property

R

relational operators

reserved word

Restore button

run time

run-time error

S

scoping

seed

separator bar

server

Settings box

shortcut key

Shortcut box

size indicator

sort order

source

split bar

statement

string comparison

String data type

string expression

Sub procedure

submenu

syntax checking

syntax error

syntax

T

tab order

text box

text file

three-dot button

title bar

twip

two's complement

type-declaration character

V

valid date separators

VarType

variable naming

variable

Variant data type

Visible check box

W

watch expression

Windows API


Programming Language


Programming Language

Operators

& Operator	/ Operator

* Operator	\ Operator

+ Operator	^ Operator

- Operator

A

Abs Function	Arithmetic Operators

AddItem Method	Arrange Method

And Operator	Asc Function

ANSI Character Set	As

Any Data Type	Atn Function

AppActivate Statement

B

Beep Statement	ByVal

C

Call Statement	Comparison Operators

ChDir Statement	Concatenation Operators

ChDrive Statement	Const Statement

Chr, Chr$ Function	Conversion Functions

Circle Method	Cos Function

Clear Method	CurDir, CurDir$ Function

Close Statement	Currency Data Type

Cls Method	CVDate Function

Command, Command$
Function

D

Data Type Conversion	Deftype Statement
Functions

Data Types	Derived Math Functions

Date, Date$ Function	Dim Statement

Date, Date$ Statement	Dir, Dir$ Function

DateSerial Function	Do...Loop Statement

DateValue Function	DoEvents Function

Day Function	DoEvents Statement

DDE Methods	Double Data Type

Declare Statement	Drag Method

E

Else	Err Function

End Statement	Err Statement

EndDoc Method	Error, Error$ Function

Environ,	Error Statement
Environ$ Function

EOF Function	Errors, Trappable

Eqv Operator	Exit Statement

Erase Statement	Exp Function

Erl Function

F

False	Fix Function

FileAttr Function	For...Next Statement

FileCopy Statement	Format, Format$ Function

FileDateTime Function	FreeFile Function

FileLen Function	Function Statement

G

Get Statement	GetText Method

GetAttr Function	Global Statement

GetData Method	GoSub...Return Statement

GetFormat Method	GoTo Statement

H

Hex, Hex$ Function	Hour Function

Hide Method

I

If...Then...Else Statement	Integer Data Type

Imp Operator	Is Operator

Input, Input$ Function	IsDate Function

Input # Statement	IsEmpty Function

InputBox,	Is
InputBox$ Function

InStr Function	IsNull Function

Int Function	IsNumeric Function

K

Kill Statement

L

LBound Function	Load Statement

LCase, LCase$ Function	LoadPicture Function

Left, Left$ Function	Loc Function

Len Function	Lock Statements

Let Statement	LOF Function

Like Operator	Log Function

Line Input Statement	Logical Operators

Line Method	Long Data Type

LinkExecute Method	LSet Statement

LinkPoke Method	LTrim, LTrim$ Function

LinkRequest Method	LTrim, LTrim$ Function

LinkSend Method

M

Math Functions	Mod Operator

Me	Month Function

Mid, Mid$ Function	Move Method

Mid$ Statement	MsgBox Function

Minute Function	MsgBox Statement

MkDir Statement

N

Name Statement	Next

New	Not Operator

NewPage Method	Now Function

O

Oct, Oct$ Function	Option Base Statement

On Error Statement	Option Compare Statement

On GoSub Statement	Option Explicit Statement

On Goto Statement	Option

On	Or Operator

Open Statement	Other Operators

Operator Precedence

P

Point Method	Private

Print # Statement	PSet method

Print Method	Put Statement

PrintForm Method

Q

QBColor Function

R

Randomize Statement	RGB Function

ReDim Statement	Right, Right$ Function

Refresh Method	RmDir Statement

Rem Statement	Rnd Function

RemoveItem Method	RSet Statement

Reset Statement	RTrim, RTrim$ Function

Resume Statement

S

SavePicture Statement	Show Method

Scale Method	Sin Function

Second Function	Single Data Type

Seek Function	Space, Space$ Function

Seek Statement	Spc Function

Select Case Statement	Sqr Function

SendKeys Statement	Static Statement

Set Statement	Step

SetAttr Statement	Stop Statement

SetData Method	Str, Str$ Function

SetFocus Method	StrComp Function

SetText Method	String, String$ Function

Sgn Function	String Data Type

Shared	Sub Statement

Shell Function

T

Tab Function	TimeSerial Function

Tan Function	TimeValue Function

TextHeight Method	To

TextWidth Method	Trappable Errors

Time, Time$ Function	True

Time, Time$ Statement	Type Statement

Timer Function

U

UBound Function	Unlock Statements

UCase, UCase$ Function	User-Defined Data Type

Unload Statement

V

Val Function	VarType Function

Variant Data Type

W

Weekday Function	Width Statement

While...Wend Statement	Write# Statement

X

XOR Operator

Y

Year Function

Z

ZOrder Method


Events


Events

A

Activate

C

Change

Click

D

DblClick

Deactivate

DragDrop

DragOver

DropDown

G

GotFocus

K

KeyDown

KeyPress

KeyUp

L

LinkClose

LinkError

LinkExecute

LinkNotify

LinkOpen

Load

LostFocus

M

MouseDown

MouseMove

MouseUp

P

Paint

PathChange

PatternChange

Q

QueryUnload

R

Resize

RowColChange

S

Scroll

SelChange

T

Timer

U

Unload

Updated


Properties


Properties

A

Action (OLE Client)	Align

ActiveControl	Archive

ActiveForm	AutoRedraw

Alignment	AutoSize

B

BackColor	BorderStyle

BackStyle	BorderWidth

BorderColor

C

Cancel	Col

Caption	Cols

CellSelected	Columns

Checked	ColWidth

Class	ControlBox

ClipControls	Count

Clip	CurrentX

ColAlignment	CurrentY

D

Data	DrawMode

DataText	DrawStyle

Default	DrawWidth

DragIcon	Drive

DragMode

E

Enabled	EXEName

Execute

F

FileName	FontItalic

FileNumber	FontName

FillColor	Fonts

FillStyle	FontSize

FixedAlignment	FontStrikethru

FixedCols	FontTransparent

FixedRows	FontUnderline

Focus	ForeColor

FontBold	Format

FontCount

G

GridLines

H

hDC	HideSelection

Height	HighLight

HelpContextID	HostName

HelpFile	hWnd

Hidden

I

Icon	Interval

Image	ItemData

Index

K

KeyPreview

L

LargeChange	LinkTopic

LeftCol	ListCount

Left	List

LinkItem	ListIndex

LinkMode	lpOLEObject

LinkTimeout

M

MaxButton	Min

Max	MousePointer

MaxLength	MultiLine

MDIChild	MultiSelect

MinButton

N

Name	Normal

NewIndex

P

Page	Pattern

Parent	Picture

PasswordChar	PrevInstance

PasteOK	Protocol

Path

R

ReadOnly	Row

RowHeight	Rows

S

ScaleHeight	ServerClass

ScaleLeft	ServerGetFormatsCount

ScaleMode	ServerGetFormats

ScaleTop	ServerProtocolCount

ScaleWidth	ServerProtocol

ScrollBars	ServerShow

Selected	ServerType

SelEndCol	ServerVerbsCount

SelEndRow	ServerVerbs

SelLength	Shape

SelStartCol	Shortcut

SelStart	SmallChange

SelStartRow	Sorted

SelText	SourceDoc

ServerAcceptFormatsCount	SourceItem

ServerAcceptFormats	Stretch

ServerClassCount	Style

ServerClassesDisplay	System

ServerClasses

T

TabIndex	Top

TabStop	TopIndex

Tag	TopRow

Text	TwipsPerPixelX

TimeOut	TwipsPerPixelY

Title

U

UpdateOptions

V

Value	Visible

Verb

W

Width	WindowState

WindowList	WordWrap

X

X1	X2

Y

Y1	Y2


Activate, Deactivate Events

See Also	Example

Apply To

Form, MDI form.

Description

Activate [image] occurs when a form becomes the active window.

Deactivate [image] occurs before a different form becomes the active window.

Syntax

Sub Form_Activate ( )

Sub MDIForm_Activate ( )

Sub Form_Deactivate ( )

Sub MDIForm_Deactivate ( )

Remarks

A form can become active by user action, such as clicking a form or control, or by using the Show or SetFocus methods in code.

The Activate event can occur only when a form is visible.  For example, a form loaded with the Load statement is not visible unless you use the Show method or set the form's Visible property to True.

TheActivate and Deactivate events occur only when moving the focus within an application.  Moving the focus to or from a form in another application does not trigger either event.  The Deactivate event does not occur when unloading a form.

The Activate event occurs before the GotFocus event; the LostFocus event occurs before the Deactivate event.

These events occur for MDI child forms only when the focus changes from one child form to another.  In an MDI form with two child forms, for example, the child forms receive these events when the focus moves between them.  However, when the focus changes between a child form and a non-MDI child form, the parent MDI form gets the Activate and Deactivate events.


See Also

Help:

GotFocus Event

LostFocus Event

SetFocus Method

Show Method

Using MDI Features

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Activate, Deactivate Events Example

The example updates a status bar with the caption of the active form.  To try this example, create a form (Form1) and a new MDI form (MDIForm1).  On the MDI form, draw a picture box containing a label.  On Form1, set the MDIChild property to True.  Paste the MDIForm_Load event code into the Declarations section of the MDI form.  Paste the Form_Activate event code into the Declarations section of the MDI child form.  Then press F5.

Sub MDIForm_Load ()

Form1.Caption = "Form #1"	' Set caption of Form1.

Dim NewForm As New Form1	' Create a new child form.

Load NewForm

NewForm.Caption = "Form #2"	' Set caption of new form.

NewForm.Show	' Display the new form.

End Sub

Sub Form_Activate ()

' Set status bar text.

MDIForm1.Label1.Caption = "Current form: " & Me.Caption

End Sub


KeyDown, KeyUp Events

See Also	Example

Apply To

Form, check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Occur when the user presses (KeyDown) or releases (KeyUp) a key while an object has the focus.  (To interpret ANSI characters, use the KeyPress event.)

Syntax

Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)

Sub ctlname_KeyDown ([Index As Integer,]KeyCode As Integer, Shift As Integer)

Sub Form_KeyUp (KeyCode As Integer, Shift As Integer)

Sub ctlname_KeyUp ([Index As Integer,]KeyCode As Integer, Shift As Integer)

Remarks

The KeyDown and KeyUp events use these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

KeyCode	A key code, such as, KEY_F1 (F1 key) and KEY_HOME (Home key).  To specify key codes, use the constants in CONSTANT.TXT, a Visual Basic file that specifies system defaults.

Shift	The state of the Shift, Ctrl, and Alt keys at the time of the event.  The Shift argument is a bit field, with the least-significant bits corresponding to the Shift key (bit 0), the Ctrl key (bit 1), and the Alt key (bit 2 ).  These bits correspond to the values 1, 2, and 4, respectively.  Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed.  For example, if both Ctrl and Alt are pressed, the value of Shift is 6.

For both events, the object with the focus receives all keystrokes.  A form can have the focus only if it has no visible and enabled controls.  Although KeyDown and KeyUp can apply to most keys, they are most often used for:

Extended character keys such as function keys.

 	Navigation keys.

Combinations of keys with standard keyboard modifiers.

Distinguishing between the numeric keypad and regular number keys.

Use KeyDown and KeyUp event procedures for keyboard handlers if you need to respond to both the pressing and releasing of a key.

KeyDown and KeyUp are not invoked for:

The Enter key if the form has a command button with the Default property set to True.

The Esc key if the form has a command button with the Cancel property set to True.

The Tab key.

If you need to test for the Shift argument, you can declare constants that define the bits within the argument by loading the CONSTANT.TXT file into a module.  The Shift constants have the following values:

Constant	Value

SHIFT_MASK	1

CTRL_MASK	2

ALT_MASK	4

The constants act as bit masks that you can use to test for any combination of buttons.  You can place the constants at the procedure level or in the Declarations section of a module where you can use this syntax:

Global Const Constantname = expression

You test for a condition by first assigning each result to a temporary integer variable and then comparing Shift to a bit mask.  Use the And operator with the Shift argument to test whether the condition is greater than 0, indicating that the modifier was pressed [image] for example:

ShiftDown = (Shift And SHIFT_MASK) > 0

In a procedure, you can test for any combination of conditions [image] for example:

If ShiftDown And CtrlDown Then

Note	If the KeyPreview property is True, a form receives these events before controls on the form receive the events.  Use the KeyPreview property to create global keyboard-handling routines.


See Also

Help:

Keyboard

KeyPreview Property

Operator Precedence

SendKeys Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


KeyDown, KeyUp Events Example

The example demonstrates a generic keyboard handler that responds to the F2 function key and to all the associated Alt, Shift, and Ctrl combinations.  To find the value of the key constants, look at the CONSTANT.TXT file or load it into a module.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Then press F5 and press F2 with the Alt  Shift, and Ctrl keys.

Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer)

Dim ShiftDown, AltDown, CtrlDown, Txt

Const KEY_F2 = &H71	' Define constants.

Const SHIFT_MASK = 1

Const CTRL_MASK = 2

Const ALT_MASK = 4

ShiftDown = (Shift And SHIFT_MASK) > 0

AltDown = (Shift And ALT_MASK) > 0

CtrlDown = (Shift And CTRL_MASK) > 0

If KeyCode = KEY_F2 Then	' Display key combinations.

If ShiftDown And CtrlDown And AltDown Then

Txt = "Shift + Ctrl + Alt F2."

ElseIf ShiftDown And AltDown Then

Txt = "Shift + Alt F2."

ElseIf ShiftDown And CtrlDown Then

Txt = "Shift + Ctrl + F2."

ElseIf CtrlDown And AltDown Then

Txt = "Ctl + Alt + F2."

ElseIf ShiftDown Then

Txt = "Shift F2."

ElseIf CtrlDown Then

Txt = "Ctrl F2."

ElseIf AltDown Then

Txt = "Alt F2."

ElseIf Shift = 0 Then

Txt = "F2."

End If

Text1.Text = "You pressed " & Txt

End If

End Sub


KeyPress Event

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Occurs when the user presses and releases an ANSI key.

Syntax

Sub Form_KeyPress (KeyAscii As Integer)

Sub control_KeyPress ([Index As Integer,]KeyAscii As Integer)

Remarks

The KeyPress event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

KeyAscii	Returns a standard numeric ANSI keycode.  KeyAscii is passed by reference; changing it sends a different character to the object.  Changing KeyAscii to 0 cancels the keystroke so that the object receives no character.

The object with the focus receives the event.  A form can receive the event only if it has no visible and enabled controls, or if the KeyPreview property is True.  A KeyPress event can involve any printable keyboard character, the Ctrl key combined with a character from the standard alphabet or one of a few special characters, and the Enter or Backspace key.  A KeyPress event procedure is useful for intercepting keystrokes entered in a text box or combo box.  It allows you to immediately test keystrokes for validity or to format characters as they are typed.  Changing the value of the argument KeyAscii changes the character displayed.

You can convert the argument KeyAscii into a character by using the expression:

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can understand by using the expression:

KeyAscii = Asc(char)

Use KeyDown and KeyUp event procedures to handle any keystroke not recognized by KeyPress, such as function keys, editing keys, navigation keys, and any combinations of these with keyboard modifiers.  Unlike the KeyDown and KeyUp events, KeyPress does not indicate the physical state of the keyboard; instead, it passes a character.

KeyPress interprets the uppercase and lowercase of each character as separate keycodes and, therefore, as two separate characters.  KeyDown and KeyUp interpret the uppercase and lowercase of each character by means of two arguments: KeyCode, which indicates the physical key (thus returning "A" and "a" as the same key); and Shift, which indicates the state of Shift+key and therefore returns either "A" or "a."

If the KeyPreview property is True, a form receives the event before controls on the form receive the event.  Use the KeyPreview property to create global keyboard-handling routines.

Note	The ANSI number for the keyboard combination of Ctrl+@ is 0.  Because Visual Basic recognizes a KeyAscii value of 0 as a null string, you should avoid using Ctrl+@ in your applications.


See Also

Help:

ANSI Table

Asc Function

Change Event

Chr, Chr$ Function

Keyboard

KeyPreview Property

SendKeys Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


KeyPress Event Example

The example converts text entered into a text box to uppercase.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Then press F5 and type something into the text box.

Sub Text1_KeyPress (KeyAscii As Integer)

Char = Chr(KeyAscii)

KeyAscii = Asc(UCase(Char))

End Sub


Load Event

See Also	Example

Applies To

Form, MDI form.

Description

Occurs when a form is loaded.  For a startup form, occurs when an application starts, as the result of a Load statement, or as the result of a reference to an unloaded form's properties or controls.

Syntax

Sub Form_Load ( )

Sub MDIForm_Load ( )

Remarks

Typically, you use a Load event procedure to include initialization code for a form [image] for example, specifying default settings for controls, indicating contents to be loaded into combo boxes or list boxes, and initializing form-level variables.

In code, when you reference a property on an unloaded form, the form is automatically loaded, but is not automatically made visible unless the MDIChild property is True.  If an MDI form is not loaded, and a child form is loaded, both the MDI form and the child form are automatically loaded and both become visible.  Other forms are not shown until you either use the Show method or set the Visible property to True.

The following code in an MDI form Load event automatically loads an MDI child form (assuming Form1 has its MDIChild property set to True):

Dim NewForm As New Form1

NewForm.Caption = "New Form"	' Loads form by reference.

Since all child forms become visible when loaded, the Caption property reference loads the form and makes it visible.

Note	When you create procedures for related events, such as Activate, GotFocus, Paint, and Resize, be sure that their actions don't conflict and that they don't cause recursive events.


See Also

Help:

Load Statement

QueryUnload Event

Unload Event

Unload Statement

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Load Event Example

The example loads items into a combo box when a form is loaded.  To try this example, paste the code into the Declarations section of a form that contains a combo box.  Then press F5.

Sub Form_Load ()

Combo1.AddItem "Mozart"	' Add items to list.

Combo1.AddItem "Beethoven"

Combo1.AddItem "Rock 'n Roll"

Combo1.AddItem "Reggae"

Combo1.ListIndex = 2	' Set default selection.

End Sub


Paint Event

See Also	Example

Applies To

Form, picture box.

Description

Occurs when part or all of a form or picturebox is exposed after it has been moved or enlarged, or after a window that was covering the object has been moved.

Syntax

Sub Form_Paint ( )

Sub ctlname_Paint ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.

A Paint procedure is useful if you have output from graphics methods in your code.  With a Paint procedure, you can ensure that such output is repainted when necessary.

If the AutoRedraw property is True, repainting or redrawing is automatic so no Paint events are necessary.  The Paint event is also invoked when the Refresh method is used.

If ClipControls is False, graphics methods in the Paint event procedure affect only newly exposed areas of the form; otherwise, the graphics methods repaint all areas of the form not covered by controls (except image, label, line, and shape controls).

Using a Refresh method in a Resize event procedure forces repainting of the entire object every time a user resizes the form.

Note	Using a Paint event procedure for certain tasks can cause a cascading event.  In general, avoid using a Paint procedure for the following:

Moving or sizing a form or control.

Changing any variables that affect size or visual appearance such as setting an object's BackColor property.

Invoking a Refresh method.

A Resize event procedure may be more appropriate for some of these tasks.


See Also

Help:

AutoRedraw Property

Circle Method

ClipControls Property

Line Method

Print Method

PSet Method

Refresh Method

Resize Event

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Paint Event Example

The example draws a diamond that intersects the center point of each side of a form and adjusts automatically as the form is resized.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and resize the form.

Sub Form_Paint ()

Dim HalfX, HalfY	' Declare variables.

HalfX = ScaleLeft + ScaleWidth / 2	' Set to half of width.

HalfY = ScaleTop + ScaleHeight / 2	' Set to half of height.

' Draw a diamond.

Line (ScaleLeft, HalfY) - (HalfX, ScaleTop)

Line -(ScaleWidth + ScaleLeft, HalfY)

Line -(HalfX, ScaleHeight + ScaleTop)

Line -(ScaleLeft, HalfY)

End Sub

Sub Form_Resize

Refresh

End Sub


QueryUnload Event

See Also	Example

Applies To

Form, MDI form.

Description

Occurs before a form or application closes.  When an application is closing, the QueryUnload event occurs first in an MDI form (if any) and then in all other forms.  If no form cancels the QueryUnload event, the Unload event then occurs first for all other forms and last for an MDI form.

Syntax

Sub Form_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Sub MDIForm_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Remarks

The QueryUnload event uses the following arguments:

Argument	Description

Cancel	Setting this argument to any value other than zero stops the QueryUnload event for all loaded forms and stops the form and application from closing.

UnloadMode	Indicates the reason for the QueryUnload event.

The UnloadMode argument can have these values:

Value	Description

0	The user has chosen the Close command from the Control-menu box on the form.

1	The Unload method has been invoked from code.

2	The current Windows-environment session is ending.

3	The Microsoft Windows Task Manager is closing the application.

4	An MDI child form is closing because the MDI form is closing.

This event is typically used to make sure there are no unfinished tasks on each form before an application closes.  For example, if a user has not yet saved some new data on any form, your application can ask the user if the data should be saved.

When an application closes, you can use either QueryUnload or Unload event procedures to set Cancel to True, stopping the closing process.  However, the QueryUnload event occurs for all forms before any are unloaded, and the Unload event occurs as each form is unloaded.


See Also

Help:

Unload Event

Unload Statement

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


QueryUnload Event Example

The example uses an MDI form containing two MDI child forms.  When you choose the Close command from the Control-menu box to close a form, you get a different message than if you choose the Exit command from the File menu.  To try this example, create an MDI form and then use the Menu Design window to create a File menu containing an Exit command named FileExit.  On Form1, set the MDIChild property to True.  Paste the code into the Declarations sections of the respective forms and press F5 to run the program.

' Paste into Declarations section of MDIForm1

Sub MDIForm_Load ()

Dim NewForm As New Form1	' New instance of Form1.

NewForm.Caption = "Form2"	' Set caption and show.

End Sub

Sub FileExit_Click ()

Unload MDIForm1	' Exit the application.

End Sub

Sub MDIForm_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Dim Msg	' Declare variable.

' Set the message text.

Msg = "Do you really want to exit the application?"

' If user clicks the 'No' button, stop QueryUnload.

If MsgBox(Msg, 36, Me.Caption) = 7 Then Cancel = True

End Sub

' Paste into Declarations section of Form1

Sub Form_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Dim Msg	' Declare variable.

If UnloadMode > 0 Then

' If exiting the application.

Msg = "Do you really want to exit the application?"

Else

' If just closing the form.

Msg = "Do you really want to close the form?"

End If

' If user clicks the 'No' button, stop QueryUnload.

If MsgBox(Msg, 36, Me.Caption) = 7 Then Cancel = True

End Sub


Scroll Event

See Also	Example

Applies To

Horizontal scroll bar, vertical scroll bar.

Description

Occurs while a user drags the box on a scroll bar.

Syntax

ctlname_Scroll ( )

Remarks

You can use this event to perform calculations or to manipulate controls that must be coordinated with ongoing changes in scroll bars.  In contrast, use the Change event when you want an update to occur only once, after a scroll bar changes.

Note	Avoid using a MsgBox statement or function in this event.


See Also

Help:

Change Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Scroll Event Example

The example changes the size of a shape control to correspond to the value of a horizontal scroll bar as you drag the box on the scroll bar.  To try this example, paste the code into the Declarations section of a form that contains a shape control, a label, and a horizontal scroll bar.  Set the Index property for the Shape control to 0 (to create a control array).  Then press F5 and move the scroll bar.

Sub Form_Load ()

' Move and size the first Shape control.

Shape1(0).Move HScroll1.Left, HScroll1.Top * 1.5, HScroll1.Width, HScroll1.Height

Label1.Caption = ""	' Set the Label caption.

Load Shape1(1)	' Create the second Shape.

' Move and size the second Shape control.

Shape1(1).Move Shape1(0).Left, Shape1(0).Top, 1, Shape1(0).Height

Shape1(1).BackStyle = 1	' Set BackStyle to Opaque.

Shape1(1).Visible = True	' Display the second Shape.

HScroll1.Min = 1	' Set Values of the Scroll bar.

HScroll1.Max = HScroll1.Width

End Sub

Sub HScroll1_Change ()

Label1.Caption = "Changed"	' Display message after change.

End Sub

Sub HScroll1_Scroll ()

Shape1(1).BackColor = &HFF0000	' Set Shape color to Blue.

Label1.Caption = "Changing"	' Display message while scrolling.

Shape1(1).Width = HScroll1.Value	' Size Shape to Scroll Value.

End Sub


Change Event

See Also	Example

Applies To

Combo box, directory list box, drive list box, horizontal scroll bar, label, picture box, text box, vertical scroll bar.

Description

Indicates that the contents of a control have changed.  How and when this event occurs varies with the control:

Combo box [image] changes the text in the text box portion of the control.  Occurs only if if the Style property is 0 (Dropdown Combo) or 1 (Simple Combo) and the user changes the text or you change the Text property from code.

Directory list box [image] changes the selected directory.  Occurs when the user double-clicks a new directory or when you change the Path property from code.

Drive list box [image] changes the selected drive.  Occurs when the user selects a new drive or when you change the Drive property from code.

Horizontal and vertical scroll bar [image] moves the scroll box portion of the scroll bar.  Occurs when the user scrolls or when you change the Value property from code.

Label [image] changes the contents of the label.  Occurs when a DDE link updates data or when you change the Caption property from code.

Picture box [image] changes the contents of the picture box.  Occurs when a DDE link updates data or when you change the Picture property from code.

Text box [image] changes the contents of the text box.  Occurs when the user changes the text or when you change the Text property from code.

Syntax

Sub ctlname_Change (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  A Change procedure can synchronize or coordinate data display among controls.  For example, you can use a scroll bar's Change procedure to update the scroll bar's Value property setting in a text box.  Or you might use a Change procedure to display data and formulas in a work area and results in another area.

Change procedures are also useful for updating properties in file-system controls.  For example, you can update the Path property for a directory list box to reflect a change in a drive list box's Drive property.

Note	A Change procedure can sometimes cause a cascading event.  This occurs when the control's Change event alters the control's contents [image] for example, by setting a property in code that determines the control's value, such as the Text property setting for a text box.  To prevent a cascading event:

If possible, avoid writing a Change procedure for a control that alters the control's contents.  If you do write such a procedure, be sure to set a flag variable that blocks out further changes while the current change is in progress.

Avoid creating two or more controls whose Change procedures affect each other [image] for example, two text boxes that update each other.

Also avoid using a MsgBox function or statement in this event for horizontal or vertical scroll bars.


See Also

Help:

KeyDown, KeyUp Events

KeyPress Event

LinkTopic Property

LostFocus Event

PathChange Event

PatternChange Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Change Event Example

The example displays the numeric setting of a horizontal scroll bar's Value property in a text box. To try this example, create a form with a text box and a horizontal scroll bar (set Min = 0, Max = 1000, LargeChange = 100, and SmallChange = 1).  To try this example, paste the code into the Declarations section of a form that contains a horizontal scroll bar and a text box.  Then press F5 and click the horizontal scroll bar.

Sub Form_Load ()

HScroll1.Min = 0	' Set Minimum.

HScroll1.Max = 1000	' Set Maximum.

HScroll1.LargeChange = 100	' Set LargeChange.

HScroll1.SmallChange = 1	' Set SmallChange.

End Sub

Sub HScroll1_Change ()

Text1.Text = HScroll1.Value

End Sub


Click Event

See Also	Example

Applies To

Form (not MDI form), check box, combo box, command button, directory list box, file list box, grid, image, label, list box, menu, OLE client, option button, picture box.

Description

Occurs when the user presses and then releases a mouse button over an object.  It may also occur when the value of a control is changed.

For a form, this event occurs when the user clicks either a blank area or a disabled control.  For a control, this event occurs when the user:

Clicks a control with the left mouse button.

Selects an item in a combo box or list box, either by pressing the arrow keys or by clicking the mouse button.

Presses the Spacebar when a command button, option button, or check box has the focus,

Presses Enter when a form has a command button with its Default property set to True.

Presses Esc when a form has a Cancel button [image] a command button with its Cancel property set to True.

Presses an access key combination for a control.  For example, if the caption of a command button is "&Go", then pressing Alt+G triggers the event.

You can also trigger the Click event in code by:

Setting a command button's Value property to True.

Setting an option button's Value property to True.

Changing a check box's Value property setting.

Syntax

Sub Form_Click ( )

Sub ctlname_Click (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, you attach a Click procedure to a command button, menu, or picture box to carry out commands and command-like actions.  For the other applicable controls, use this event to trigger actions in response to a change in the control.

You can use a control's Value property to test for the state of the control from code.  When a Click event is generated for a file list box, list box, label, or picture box, Visual Basic also calls the related events in this order:  MouseDown, MouseUp, Click.  When you're attaching procedures for these related events, be sure that their actions don't conflict.

Note	To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.


See Also

Help:

Cancel Property

DblClick Event

Default Property

Mousedown, MouseUp Events

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


Click Event Example

In this example, each time a picture box is clicked it moves diagonally across a form.  To try this example, paste the code into the Declarations section of a form that contains a picture box positioned at the lower left corner of the form.  Then press F5 and click the picture box.

Sub Picture1_Click ()

Picture1.Move Picture1.Left + 750, Picture1.Top - 550

End Sub


DblClick Event

See Also	Example

Applies To

Form (not MDI form), combo box, file list box, grid,image, label, list box, OLE client, option button, picture box.

Description

Occurs when the user presses and releases a mouse button and then presses and released it again over an object.

For a form, the DblClick event occurs when the user double-clicks a disabled control or a blank area of a form.  For a control, it occurs when the user:

Double-clicks a control with the left mouse button.

Double-clicks an item in a combo box whose Style property = 1 (Simple); in a file list box; or in a list box.

Syntax

Sub Form_DblClick ( )

Sub ctlname_DblClick (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  You can use a DblClick event procedure for an "implied action" such as double-clicking an icon to open a window or document.  This type of procedure is also useful for carrying out multiple steps with a single action, such as double-clicking to select an item in a list box and to close the dialog box.

To produce such shortcut effects in Visual Basic, you can use a DblClick procedure for a list box or file list box in tandem with a default button [image] a command button with its Default property set to True.  As part of the DblClick procedure for the list box, you simply call the default button's Click procedure.

For those objects that receive mouse events, the events occur in this order: MouseDown, Click, MouseUp, and DblClick.

If DblClick does not occur within the system's double-click time limit, the object recognizes another Click event.  The double-click time limit may vary because the user can set the double-click speed with the Control Panel.  When you are attaching procedures for these related events, be sure that their actions don't conflict.  Controls that do not receive DblClick events may receive two clicks instead of a DblClick.

Note	To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.


See Also

Help

Click Event

MouseDown, MouseUp Events

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DblClick Event Example

The example displays a selected list item in a text box when either a command button is clicked or a list item is double-clicked.  To try this example, paste the code into the Declarations section of a form that contains list box, a text box and a command button.  Then press F5 and click the command button or double click a list box item.

Sub Form_Load ()

List1.AddItem "John"	' Add list box entries.

List1.AddItem "Paul"

List1.AddItem "George"

List1.AddItem "Ringo"

End Sub

Sub List1_DblClick ()

Command1.Value = True	' Trigger Click event.

End Sub

Sub Command1_Click ()

Text1.Text = List1.Text	' Display selection.

End Sub


DragDrop Event

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Occurs when a drag-and-drop operation is completed as a result of dragging a control over a form or control and releasing the mouse button; or using the Drag method with its action argument = 2 (Drop).

Syntax

Sub Form_DragDrop (Source As Control, X As Single, Y As Single)

Sub MDIForm_DragDrop (Source As Control, X As Single, Y As Single)

Sub ctlname_DragDrop ([Index As Integer,]Source As Control, X As Single, Y As Single)

Remarks

The DragDrop event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Source	The control being dragged.  You can refer to properties and methods with this argument [image] for example, Source.Visible = 0.

X, Y	The current horizontal (X) and vertical (Y) position of the mouse pointer within the target form or control.  These coordinates are always expressed in terms of the target's coordinate system as set by the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties.

Use a DragDrop event procedure to control what happens after a drag operation has been completed.  For example, you can move the source control to a new location or copy a file from one location to another.

When multiple controls can potentially be used in a Source argument:

Use the TypeOf reserved word with the If statement to determine the type of control used with Source.

Use the control's Tag property to identify a control, and then use a DragDrop procedure.

Note	Use the DragMode property and Drag method to specify the way dragging is initiated.  Once dragging has been initiated, you can handle events that precede a DragDrop event with a DragOver procedure.


See Also

Help:

Drag Method

DragIcon Property

DragMode Property

DragOver Event

MouseDown, MouseUp Events

MouseMove Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DragDrop Event Example

The example demonstrates the visual effect of dropping a picture box onto another picture box.  To try this example, paste the code into the Declarations section of a form that contains three picture box controls.  Set the DragMode property for Picture1 and Picture2 to 1 (Automatic)  Use the Picture property to assign bitmaps to Picture1 and Picture2.  Then press F5 and drag Picture1 or Picture2 over Picture3..

Sub Picture3_DragDrop (Source As Control, X as Single, Y As Single)

If TypeOf Source Is PictureBox Then

' Set Picture3 bitmap to same as source control.

Picture3.Picture = Source.Picture

End If

End Sub


DragOver Event

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE Client, option button, picture box, text box, vertical scroll bar.

Description

Occurs when a drag-and-drop operation is in progress.  You can use this event to monitor when the mouse pointer enters, leaves, or is directly over a valid target.  The mouse pointer position determines which target object receives this event.

Syntax

Sub Form_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Sub MDIForm_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Sub ctlname_DragOver ([Index As Integer,]Source As Control, X As Single, Y As Single, State As Integer)

Remarks

The DragOver event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Source	The control being dragged.  You can refer to properties and methods with this argument [image] for example, Source.Visible = False.

X, Y	The current horizontal (X) and vertical (Y) position of the mouse pointer within the target form or control.  These coordinates are always expressed in terms of the target's coordinate system as set by the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties.

State	The transition state of the control being dragged in relation to a target form or control:

0 - Enter (source control is being dragged within the range of a target).

1 - Leave (source control is being dragged out of the range of a target).

2 - Over (source control has moved from one position in the target to another).

Use a DragOver event procedure to determine what happens after dragging is initiated and before a control drops onto a target.  For example, you might verify a valid target range by highlighting the target (set the BackColor or ForeColor property from code) or by displaying a special drag pointer (set the DragIcon or MousePointer property from code).

Use the argument State to determine actions at key transition points.  For example, you might highlight a possible target on State 0 (Enter) and restore the object's previous appearance on State 1 (Leave).

When an object receives a DragOver event with State = 0 (Enter):

If the source control is dropped on a valid target, a DragDrop event is generated.

If the source control is not dropped on a valid target, another DragOver event is generated with State = 1 (Leave).

Note	Use the DragMode property and Drag method to specify the way dragging is initiated.  For suggested techniques with the Source argument, see the Remarks for the DragDrop Event topic.


See Also

Help:

Drag Method

DragDrop Event

DragIcon Property

DragMode Property

MouseDown, MouseUp Events

MouseMove Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DragOver Event Example

The example demonstrates one way to indicate a valid drop target.  The drag pointer changes from the default arrow to a special icon when a text box is dragged over a picture box.  The drag pointer returns to the default when the source is dragged elsewhere.  To try this example, paste the code into the Declarations section of a form that contains a small text box and a picture box.  Set the text box DragMode property to 1.  Then press F5 and drag the text box over the picture box.

Sub Picture1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Const ENTER = 0	' Define constants.

Const LEAVE = 1

Select Case State

Case ENTER

' Load icon.

Source.DragIcon = LoadPicture("ICONS\ARROWS\POINT03.ICO")

Case LEAVE

Source.DragIcon = LoadPicture()	' Unload icon.

End Select

End Sub

Sub Picture1_DragDrop (Source As Control, X As Single, Y As Single)

Source.DragIcon = LoadPicture()	' Unload icon.

End Sub


DropDown Event

See Also	Example

Applies To

Combo box.

Description

Occurs when the list portion of a combo box is about to drop down; this event does not occur if a combo box's Style property is set to 1 (Simple Combo).

Syntax

Sub ctlname_DropDown (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Use a DropDown procedure to make final updates to a combo box list before the user makes a selection.  This allows you to add or remove items from the list, using the AddItem or RemoveItem methods.  This flexibility is useful when you want some interplay between controls [image] for example, if what you want to load into a combo box list depends on what the user selects in an option button group.


See Also

Help:

Style Property

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DropDown Event Example

The example updates a combo box based on the user's selection in an option button group.  To try this example, paste the code into the Declarations section of a form that contains a combo box and two option buttons.  Set the Name property of both option buttons to OptionGroup.  Then press F5 and click the option buttons.  The combo box reflects different carriers depending on the option button selected.

Sub Form_Load ()

Combo1.Text = ""	' Clear combox box.

End Sub

Sub Combo1_DropDown ()

While Combo1.ListCount	' Delete existing items.

Combo1.RemoveItem 0

Wend

If OptionGroup(0).Value = True Then

Combo1.AddItem "Gray Goose Express", 0

Combo1.AddItem "Wild Fargo Carriers", 1

Else

Combo1.AddItem "Pegasus Overnight"

End If

End Sub


GotFocus Event

See Also	Example

Applies To

Form (not MDI form), check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Occurs when an object receives the focus, either by user action such as tabbing to or clicking the object, or by changing the focus in code using the SetFocus method.  Note that a form receives the focus only when all visible controls are disabled.

Syntax

Sub Form_GotFocus ( )

Sub ctlname_GotFocus (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, you use a GotFocus procedure to specify the actions that occur when a control or form first receives the focus.  For example, by attaching a GotFocus procedure to each control on a form, you can guide the user by displaying brief instructions or status bar messages.  You can also provide visual cues by enabling, disabling, or showing other controls that depend on the control that has the focus.

Note	An object can receive the focus only if its Enabled and Visible properties are set to True.  To customize Visual Basic's keyboard interface for moving the focus, set the Tab order or specify access keys for controls on a form.


See Also

Help:

ActiveControl Property

ActiveForm Property

LostFocus Event

TabIndex Property

TabStop Property


GotFocus Event Example

The example displays a status bar message when a button in an option group gets the focus.  To try this example, paste the code into the Declarations section of a form that contains two option buttons and a label.  Set the Name property for both option buttons to OptionGroup. Then press F5 and click the option buttons.

Sub Form_Load ()

Label1.AutoSize = True

End Sub

Sub OptionGroup_GotFocus (Index As Integer)

Select Case Index

Case 0

Label1.Caption = "Option 1 has the focus."

Case 1

Label1.Caption = "Option 2 has the focus."

End Select

End Sub

Sub OptionGroup_LostFocus (Index As Integer)

Label1.Caption = ""

End Sub


LostFocus Event

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Occurs when an object loses the focus, either by user action such as tabbing to or clicking another object, or by changing the focus in code using the SetFocus method.

Syntax

Sub Form_LostFocus ( )

Sub ctlname_LostFocus ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.  A LostFocus procedure is primarily useful for verification and validation updates.  Using LostFocus can cause validation to take place as the user leaves the control.  Another use for this type of procedure is enabling, disabling, hiding, and displaying other objects, as in a GotFocus procedure.  You can also reverse or change conditions that you set up in the object's GotFocus procedure.


See Also

Help:

ActiveControl Property

ActiveForm Property

GotFocus Event

SetFocus Method

TabIndex Property

TabStop Property


LostFocus Event Example

The example changes the color of a text box when it receives or loses the focus (selected with the mouse or Tab key) and displays the appropriate text in the label.  To try this example, paste the code into the Declarations section of a form that contains two text boxes and a label..  Then press F5 and move the focus between Text1 and Text1.

Sub Text1_GotFocus ()

' Show focus in red.

Text1.BackColor = RGB(255, 0, 0)

Label1.Caption = "Text1 has the focus."

End Sub

Sub Text1_LostFocus ()

' Show non-focus in blue.

Text1.BackColor = RGB(0, 0, 255)

Label1.Caption = "Text1 does not have the focus."

End Sub


MouseDown, MouseUp Events

See Also	Example

Apply To

Form (not MDI form), directory list box, file list box, grid, image, label, list box, OLE client, picture box.

Description

Occur when the user presses (MouseDown) or releases (MouseUp) a mouse button.

Syntax

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub ctlname_MouseDown ([Index As Integer,]Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub ctlname_MouseUp ([Index As Integer,]Button As Integer, Shift As Integer, X As Single, Y As Single)

Remarks

The MouseDown and MouseUp events use these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Button	The button was pressed (MouseDown) or released (MouseUp) to cause the event.  The Button argument is a bit field with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2) [image] values 1, 2, and 4, respectively.  Only one of the bits is set, indicating which button caused the event.

Shift	The state of the Shift, Ctrl and Alt keys when the button specified in the Button argument was pressed or released.  A bit is set if the key is down.  The Shift argument is a bit field, with the least-significant bits corresponding to the Shift key (bit 0), the Ctrl key (bit 1), and the Alt key (bit 2 ).  These bits correspond to the values 1, 2, and 4, respectively.  Shift indicates the state of these keys.  Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed.  For example, if both Ctrl and Alt were pressed, the value of Shift would be 6.

X, Y	The current location of the mouse pointer. X and Y are always expressed in terms of the coordinate system set by the ScaleHeight, Scale Width, ScaleLeft, and ScaleTop properties of the object.

Use a MouseDown or MouseUp procedure to specify actions to occur when a given mouse button is pressed or released.  Unlike the Click and DblClick events, MouseDown and MouseUp events allow you to distinguish between the left, right, and middle mouse buttons.  You can also write code for mouse-keyboard combinations that use the Shift, Ctrl, and Alt keyboard modifiers.

The following applies to both Click and DblClick events:

If a mouse button is pressed while the pointer is over a form or control, that object "captures" the mouse and receives all mouse events up to and including the last MouseUp event.  This implies that the X, Y mouse-pointer coordinates given by a mouse event may not always be in the client area of the object that receives them.

If mouse buttons are pressed in succession, the object that captures the mouse after the first press receives all mouse events until all buttons are released.

If you need to test for the Button or Shift arguments, you can declare constants that define the bits within the argument by loading the CONSTANT.TXT file into a module.  These mouse button constants have the following values:

Constant	Value

LEFT_BUTTON	1

RIGHT_BUTTON	2

MIDDLE_BUTTON	4

SHIFT_MASK	1

CTRL_MASK	2

ALT_MASK	4

These constants are in CONSTANT.TXT.  The constants then act as bit masks you can use to test for any combination of buttons without having to figure out the unique bit field value for each combination.

Note	You can use a MouseMove procedure to respond to an event caused by moving the mouse.  The Button argument for MouseDown and MouseUp differs from the Button argument used for MouseMove.  For MouseDown or MouseUp, the Button argument indicates exactly one button per event; for MouseMove, it indicates the current state of all buttons.


See Also

Help:

Click Event

DblClick Event

MouseMove Event

MousePointer Property

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


MouseDown, MouseUp Events Example

The example demonstrates a simple paint application.  The MouseDown procedure works with a related MouseMove procedure to paint when any mouse button is pressed and dragged.  The MouseUp procedure turns off the paintbrush.  To try this example, paste the code into the Declarations section of a form.  Then press F5, click the form and move the mouse while the mouse button is depressed.

Dim PaintNow As Integer

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = True	' Paintbrush on.

End Sub

Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = False	' Turn off painting.

End Sub

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

If PaintNow Then

PSet (X, Y)	' Draw a point.

End If

End Sub

Sub Form_Load ()

DrawWidth = 10	' Use wider paintbrush.

ForeColor = RGB(0, 0, 255)	' Set drawing color.

End Sub


MouseMove Event

See Also	Example

Applies To

Form (not MDI form), directory list box, file list box, grid, image, label, list box, OLE client, picture box.

Description

Occurs when the user moves the mouse.

Syntax

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub ctlname_MouseMove ([Index As Integer,]Button As Integer, Shift As Integer, X As Single, Y As Single)

Remarks

The MouseMove event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Button	The state of the mouse buttons, in which a bit is set if the button is down.  The Button argument is a bit field, with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2) [image] values 1, 2, and 4, respectively.  It indicates the complete state of the mouse buttons; some, all, or none of these three bits can be set, indicating that some, all, or none of the buttons is pressed.

Shift	The state of the Shift, Ctrl and Alt keys: Bit is set if the key is down.  The Shift argument is a bit field, with the least-significant bits corresponding to the Shift key (bit 0), the Ctrl key (bit 1), and the Alt key (bit 2 ).  These bits correspond to the values 1, 2, and 4, respectively.  Shift indicates the state of these keys.  Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed.  For example, if both Ctrl and Alt were pressed, the value of Shift would be 6.

X ,Y	The current location of the mouse pointer.  X and Y are always expressed in terms of the coordinate system set by the ScaleHeight, Scale Width, ScaleLeft, and ScaleTop properties of the object.

The MouseMove event is generated continually as the mouse pointer moves across objects.  Unless another object has captured the mouse, an object recognizes a MouseMove event whenever the mouse position is within its borders.

If you need to test for the Button or Shift arguments, you can declare constants that define the bits within the argument by loading the CONSTANT.TXT file into a module.  These mouse button constants have the following values:

Constant	Value

LEFT_BUTTON	1

RIGHT_BUTTON	2

MIDDLE_BUTTON	4

SHIFT_MASK	1

CTRL_MASK	2

ALT_MASK	4

These are in CONSTANT.TXT.  The constants 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 [image] for example:

LeftDown = (Button And LEFT_BUTTON) > 0
CtrlDown = (Shift And CTRL_MASK) > 0

Then, in a procedure, you can test for any combination of conditions [image] for example:

If LeftDown And CtrlDown Then

Note	You can use MouseDown and MouseUp event procedures to respond to events caused by pressing and releasing mouse buttons.

The Button argument for MouseMove differs from the Button argument used for MouseDown and MouseUp.  For MouseMove, the Button argument indicates the current state of all buttons; a single MouseMove event may indicate that some, all, or no button is pressed.  For MouseDown or MouseUp, the Button argument indicates exactly one button per event.


See Also

Help:

Click Event

DblClick Event

MousePointer Property

MouseUp, MouseDown Events

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


MouseMove Event Example

The example demonstrates a simple paint application.  The MouseDown procedure works with a related MouseMove procedure to paint when any mouse button is pressed.  The MouseUp procedure turns off the paintbrush.  To try this example, paste the code into the Declarations section of a form.  Then press F5, click the form and move the mouse while the mouse button is depressed.

Dim PaintNow As Integer	' Declare variable.

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = True	' Paintbrush on.

End Sub

Sub Form_MouseUp (Button As Integer, X As Single, Y As Single)

PaintNow = False	' Turn off painting.

End Sub

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

If PaintNow Then

PSet (X, Y)	' Draw a point.

End If

End Sub

Sub Form_Load ()

DrawWidth = 10	' Use wider paintbrush.

ForeColor = RGB(0, 0, 255)	' Set drawing color.

End Sub


PathChange Event

See Also	Example

Applies To

File list box.

Description

Occurs when the path changes by setting the FileName or Path properties from code.

Syntax

Sub ctlname_PathChange ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.  You can use a PathChange procedure to respond to path changes in a file list box.  When you assign a string containing a new path to the FileName property, the file list box control invokes the PathChange event.


See Also

Help:

FileName Property

Path Property

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"


PathChange Event Example

The example demonstrates how to update a label control to reflect the current path for a file list box.  Double-clicking a directory name displays a list of that directory's files in the file list box; it also displays the directory's complete path in the label control.  To try this example, paste the code into the Declarations section of a form that contains a label, a directory list box and a file list box.  Then press F5.

Sub File1_PathChange ()

Label1.Caption = "Path: " & Dir1.Path	' Show path in label.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set file path.

End Sub

Sub Form_Load ()

Label1.Caption = "Path: " & Dir1.Path	' Show path in label.

End Sub


PatternChange Event

See Also	Example

Applies To

File list box.

Description

Occurs when the file listing pattern (such as "*.*") has changed by setting the FileName or Pattern properties from code.

Syntax

Sub ctlname_PatternChange (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  You can use a PatternChange procedure to respond to pattern changes in a file list box.  When you assign a string containing a new pattern to the FileName property, the file list box invokes the PathChange event.


See Also

Help:

FileName Property

Path Property

PathChange Event

Pattern Property

Programmer's Guide:

Chapter 18, "Using the File-System Controls"


PatternChange Event Example

The example updates a file list box with files matching the pattern typed into a text box.  If a full path is entered into the text box, such as c:\bin\*.exe, the text is automatically parsed into path and pattern components.  To try this example, paste the code into the Declarations section of a form that contains a text box, a label, a file list box, and a command button.  Then press F5 and type a valid file pattern into the text box

Sub Form_Load ()

Command1.Default = True	' Set Default property.

Command1.Caption = "OK"	' Set Caption.

Command1.Default = True	' Set Default.

End Sub

Sub Command1_Click ()	' OK button clicked.

' Text is parsed into path and pattern components.

File1.FileName = Text1.Text

Label1.Caption = "Path: " & File1.Path

End Sub

Sub File1_PatternChange ()

Text1.Text = File1.Pattern	' Set text to new pattern.

End Sub


Resize Event

See Also	Example

Applies To

Form, MDI Form, picture box.

Description

Occurs when the size of the form or picture box changes.  This event also occurs when the form first appears.

Syntax

Sub {Form|MDIForm|picturebox}_Resize ( )

Remarks

Use a Resize procedure when you need to move or resize controls when the parent form itself is resized.  A Resize procedure can also be used to recalculate variables or properties (such as ScaleHeight and ScaleWidth) that may depend on the size of the form.  To invoke the Paint event every time a form is resized, use the Refresh method in a Resize event if you want graphics to maintain sizes proportional to the form when the form is resized.

Whenever the AutoRedraw property is set to False and the form is resized, Visual Basic also calls the related events in this order: Resize, Paint.  When you are attaching procedures for these related events, be sure that their actions don't conflict.


See Also

Help:

AutoRedraw Property

Load Statement

Paint Event

Refresh Method

Show Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Resize Event Example

The example automatically resizes a text box to fill the form whenever the form is resized.  To try this example, paste the code into the Declarations section of a form that contains a textbox.  Set the textbox MultiLine property to True, the ScrollBars property to 3, and the BorderStyle to 0.  Then press F5 and resize the form.

Sub Form_Load ()

Text1.Text = ""	' Clear text.

End Sub

Sub Form_Resize ()

Text1.Move 0,0, ScaleWidth, ScaleHeight

End Sub


Timer Event

See Also	Example1	Example2

Applies To

Timer.

Description

Occurs when a preset interval for a timer control has elapsed.  The interval's frequency is stored in the control's Interval property, which specifies the length of time in milliseconds.

Syntax

Sub ctlname_Timer ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Use this procedure to tell Visual Basic what to do at every timer Interval.  When you are working with the Timer event:

The Interval property specifies the interval between Timer events in milliseconds.

Whenever the timer control's Enabled property is set to True and the Interval is greater than zero, the Timer event waits for the period specified in the Interval property.


See Also

Help:

Enabled Property

Interval Property

Timer Function

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


Timer Event Example 1

The example demonstrates a digital clock.  To try this example, paste the code into the Declarations section of a form that contains a label and a timer control.  Then press F5.

Sub Form_Load ()

Timer1.Interval = 1000	' Set timer interval.

End Sub

Sub Timer1_Timer ()

Label1.Caption = Time	' Update time display.

End Sub


Timer Event Example 2

This example moves a picture box across a form.  To try this example, paste the code into the Declarations section of a form that contains a timer and a picture control.  Then press F5.  For a better visual effect you can assign a bitmap to the picture box using the Picture property.

Dim DeltaX, DeltaY As Integer	' Declare variables.

Sub Timer1_Timer ()

Picture1.Move Picture1.Left + Deltax, Picture1.Top + DeltaY

If Picture1.Left < ScaleLeft Then DeltaX = 100

If Picture1.Left + Picture1.Width > ScaleWidth + ScaleLeft Then

DeltaX = -100

End If

If Picture1.Top < ScaleTop Then DeltaY = 100

If Picture1.Top + Picture1.Height > ScaleHeight + ScaleTop Then

DeltaY = -100

End If

End Sub

Sub Form_Load ()

Timer1.Interval = 1000	' Set Interval.

DeltaX = 100	' Initialize variables.

DeltaY = 100

End Sub


Unload Event

See Also	Example

Applies To

Form, MDI Form.

Description

Occurs when a form is about to be removed from the screen.  When that form is reloaded, the contents of all its controls are reinitialized.  This event is triggered by user action (closing the form using the Control-menu box), or by an Unload statement.

Syntax

Sub {Form|MDIForm}_Unload (Cancel As Integer)

Remarks

Setting Cancel to any nonzero value prevents the form from being removed.

Use an Unload event procedure to verify that the unloading of the form should proceed or to specify actions that should take place when the form is unloaded.  You can also include any form-level validation code you might need for closing the form or saving the data in it to a file.

The QueryUnload occurs before the Unload.

The Unload event can be caused by using the Unload statement, or by the user taking an action such as choosing the Close command on a form's Control menu, exiting the application with End Task button on the Windows Task Manager, closing the MDI form for which the current form is a child form, or exiting the Windows environment while the application is running.


See Also

Help:

Load Event

Load Statement

QueryUnload Event

Unload Statement

Programmer's Guide:

Chapter 18, "Using the File-System Controls"


Unload Event Example

The example demonstrates a simple procedure to close a form while querying the user with various message boxes.  In an actual application, you could add calls to general-purpose Sub procedures that emulate the processing of the Exit, Save, and Save As commands on Visual Basic's File menu.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Once the form is displayed, press Alt + F4 to close the form.

Sub Form_Unload (Cancel As Integer)

Dim Msg, Response	' Declare variables.

Msg = "Save Data before closing?"

Response = MsgBox(Msg, 3 + 32, "Save Dialog")

Select Case Response

Case 2	' Do not allow close.

Cancel = -1

Msg = "Command has been cancelled."

Case 6

' Enter code to save data here.

Msg = "Data saved."'

Case 7

Msg = "Data not saved."

End Select

MsgBox Msg, 0, "Confirm"	' Display message.

End Sub


Trappable Errors


Trappable Errors

See Also

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

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

Code	Message

3	Return without GoSub

5	Illegal function call

6	Overflow

7	Out of memory

9	Subscript out of range

10	Duplicate definition

11	Division by zero

13	Type mismatch

14	Out of string space

16	String formula too complex

17	Can't continue

19	No Resume

20	Resume without error

28	Out of stack space

35	Sub or Function not defined

48	Error in loading DLL

49	Bad DLL calling convention

51	Internal error

52	Bad file name or number

53	File not found

54	Bad file mode

55	File already open

57	Device I/O error

58	File already exists

59	Bad record length

61	Disk full

62	Input past end of file

63	Bad record number

64	Bad file name

67	Too many files

68	Device unavailable

70	Permission denied

71	Disk not ready

74	Can't rename with different drive

75	Path/File access error

76	Path not found

91	Object variable not set

92	FOR loop not initialized

93	Invalid pattern string

94	Invalid use of Null

95	Cannot destroy active form instance

281	No More DDE channels

282	No foreign application responded to a DDE initiate

283	Multiple applications responded to a DDE initiate

284	DDE channel locked

285	Foreign application won't perform DDE method or operation

286	Timeout occured while waiting for DDE response

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

294	Invalid DDE Link format

295	Message queue filled; DDE message lost

298	DDE requires DDEML.DLL

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

321	Invalid file format

341	Invalid object array index

342	Not enough room to allocate control array 'item'

343	Object not an array

344	Must specify index for object array

360	Object already loaded

361	Can't load or unload this object

362	Can't unload controls created at design time

363	Custom control 'item' not found

364	Object was unloaded

365	Unable to unload within this context

380	Invalid property value

382	'item' property cannot be set at run time

383	'item' property is read-only

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

385	Must specify index when using property array

386	'item' property not available at run time

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

388	Can't set Visible property from a parent menu

391	Name not available.

392	MDI Child forms cannot be hidden

393	'item' property cannot be read at runtime

394	'item' property is write-only

400	Form already displayed; can't show modally

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

402	Must close or hide topmost modal form first

403	MDI forms cannot be shown modally

404	MDI child forms cannot be shown modally.

420	Invalid object reference

421	Method not applicable for this object

422	Property 'item' not found

424	Object required

425	Invalid object use

426	Only one MDI form allowed

460	Invalid clipboard format

461	Specified format does not match format of data

480	Can't create AutoRedraw image

481	Invalid picture

482	Printer error

600	Set value not allowed on collections

601	Get Value not allowed on collections

602	General ODBC error: '|'

603	ODBC - SQLAllocEnv failure

604	ODBC - SQLAllocConnect failure

605	OpenDatabase - invalid connect string

606	ODBC - SQLConnect failure '|'

607	Access attempted on unopened DataBase

608	ODBC - SQLFreeConnect error

609	ODBC - GetDriverFunctions failure

610	ODBC - SQLAllocStmt failure

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

612	ODBC - SQLBindCol failure

613	ODBC - SQLFetch failure: '|'

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

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

616	Table exists - append not allowed

617	No fields defined - cannot append table

618	ODBC - SQLNumResultCols (Create Dynaset) failure: '|'

619	ODBC - SQLDescribeCol (Create Dynaset) failure '|'

621	Row-returning SQL is illegal in ExecuteSQL method

622	CommitTrans/Rollback illegal - Transactions not support

623	Name not found in this collection

624	Unable to Build Data Type Table

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

626	Attempt to Move past EOF

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

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

629	Warning: | (ODBC - SQLSetConnectOption failure)

630	Property is read-only

631	Zero rows affected by Update method

632	Update illegal without previous Edit or AddNew method

633	Append illegal - field is part of a TableDefs collection

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

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

636	Set field value illegal without previous Edit or AddNew method

637	Append illegal - Index is part of a TableDefs collection

638	Access attempted on unopened Dynaset

639	Field type is illegal

640	Field size illegal for specified Field Type

641	| illegal - no current record

642	Reserved parameter must be FALSE

643	Property Not Found

644	ODBC - SQLConfigDataSource error '|'

645	ODBC Driver does not support exclusive access to Dynasets

646	GetChunk: Offset/Size argument combination illegal

647	Delete method requires a name argument

648	ODBC Objects require VBODBCA.DLL

708	File not found: |

710	File already open: |

712	Device IO error: |

713	File already exists: |

716	Disk full: |

719	Bad file name: |

722	Too many files: |

725	Permission denied: |

730	Path access error: |

731	Path not found: |

732	Must have startup form or Sub Main()

735	Can't save file to TEMP

740	Invalid procedure name

742	Not enough room to paste contents into current line

743	Unable to set next statement

744	Search text not found

745	Text would be too long. Edit prevented

746	One or more replacements too long and not made

747	Syntax errors produced while replacing

748	An undo error has occurred. Further undo is unavailable

749	Watch expression too long. Expression truncated.

750	An expression must be selected

752	Error reading Tutorial file 'item'

753	Tutorial directory 'item' not found

754	Can't find Tutorial file 'item'

755	Not enough memory to load Tutorial

756	Duplicate procedure name

757	Can't find Windows Help .EXE file

758	Control must be same type as rest of array

759	Array already has a control at index 'item'

760	Not a legal object name: 'item'

761	Must specify which item(s) to print

762	Can't clear INDEX property without changing NAME

764	| is a control name

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

766	Event handler must be a Sub procedure

768	Event procedure argument has incorrect data type

769	Menu subitem skipped a level

770	Can't put check mark here

771	Can't assign shortcut key to menu name

772	Can't use separator bar as menu name

773	Menu control must have a name

774	Menu control array element must have an index

775	Menu control array indices must be in ascending order

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

777	Shortcut key already assigned

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

779	At least one submenu item must be visible

780	Valid Range: [1..32]

781	Valid Range:[24..1188]

783	Separator may not be the Window List menu

784	Can't have more than one Window List menu

785	New not allowed on this type

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

20001	Can't unload Custom Control DLL; in use

20002	Can't quit at this time

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

20004	'item' has been changed; must reset

20005	Reset halted programs so Code window can be closed?

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

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

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

20009	Search complete

20011	Invalid command-line argument 'item'

20012	Save changes to 'item'?

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

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

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

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

20017	Form had old file format

20018	Replace existing 'item'?

20019	'item' does not exist

20020	'item' already exists in project

20021	'|' is a Read-Only file

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

20023	'|' could not be loaded

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

20025	String value to long to process; form load aborted

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

Grid Messages

30000	Cannot use 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	Cannot remove last non-fixed row

30016	FixedRows must be one less than Rows value

30017	FixedCols must be one less than Cols value

30018	Rows must be one more than FixedRows value

30019	Cols must be one more than FixedCols value

OLE Client Messages

30000	OLE_OK

30001	OLE_WAIT

30002	OLE_BUSY

30003	OLE_ERROR_PROTECT_ONLY

30004	OLE_ERROR_MEMORY

30005	OLE_ERROR_STREAM

30006	OLE_ERROR_STATIC

30007	OLE_ERROR_BLANK

30008	OLE_ERROR_DRAW

30009	OLE_ERROR_METAFILE

30010	OLE_ERROR_ABORT

30011	OLE_ERROR_CLIPBOARD

30012	OLE_ERROR_FORMAT

30013	OLE_ERROR_OBJECT

30014	OLE_ERROR_OPTION

30015	OLE_ERROR_PROTOCOL

30016	OLE_ERROR_ADDRESS

30017	OLE_ERROR_NOT_EQUAL

30018	OLE_ERROR_HANDLE

30019	OLE_ERROR_GENERIC

30020	OLE_ERROR_CLASS

30021	OLE_ERROR_SYNTAX

30022	OLE_ERROR_DATATYPE

30023	OLE_ERROR_PALETTE

30024	OLE_ERROR_NOT_LINK

30025	OLE_ERROR_NOT_EMPTY

30026	OLE_ERROR_SIZE

30027	OLE_ERROR_DRIVE

30028	OLE_ERROR_NETWORK

30029	OLE_ERROR_NAME

30030	OLE_ERROR_TEMPLATE

30031	OLE_ERROR_NEW

30033	OLE_ERROR_OPEN

30034	OLE_ERROR_NOT_OPEN

30035	OLE_ERROR_LAUNCH

30036	OLE_ERROR_COMM

30037	OLE_ERROR_TERMINATE

30038	OLE_ERROR_COMMAND

30039	OLE_ERROR_SHOW

30040	OLE_ERROR_DOVERB

30041	OLE_ERROR_ADVISE_NATIVE

30042	OLE_ERROR_ADVISE_PICT

30043	OLE_ERROR_ADVISE_RENAME

30044	OLE_ERROR_POKE_NATIVE

30045	OLE_ERROR_REQUEST_NATIVE

30046	OLE_ERROR_REQUEST_PICT

30047	OLE_ERROR_SERVER_BLOCKED

30048	OLE_ERROR_REGISTRATION

30050	OLE_ERROR_TASK

30051	OLE_ERROR_OUTOFDATE

30052	OLE_ERROR_CANT_UPDATE_CLIENT

30053	OLE_ERROR_UPDATE

31001	Out of memory

31002	Property is write only

31003	Can't open Clipboard

31004	No object

31005	Object closed

31007	Can't paste

31008	Invalid property value

31009	Object not empty

31010	Property is read-only

31011	Type of object cannot be created

31014	This action is reserved for future use

31015	Cannot execute object

31016	Server class was not specified before the registration database was accessed

31017	Invalid format on set data or set data text

31018	Class is not set

31019	Source document is not set

31020	Source item is not set


See Also

Help:

Err Statement

Error Statement

Error$ Function

Resume Statement

Programmer's Guide:

Chapter 9, "Debugging"

Chapter 10, "Handling Run-Time Errors"


Archive, Hidden, Normal, ReadOnly, System Properties

See Also

Apply To

File list box.

Description

Determine whether a file list box contains files with Archive, Hidden, Normal, ReadOnly, or System attributes.

Usage

[form.]filelistbox.Archive[ = boolean ]

[form.]filelistbox.Hidden[ = boolean ]

[form.]filelistbox.Normal[ = boolean ]

[form.]filelistbox.ReadOnly[ = boolean ]

[form.]filelistbox.System[ = boolean ]

Setting

The property settings are:

Setting	Description

True	(Default for Archive, Normal, and ReadOnly) Displays files with the property's attribute in the file list box.

False	(Default for Hidden and System) Does not display files with the property's attribute in the file list box.

Remarks

Use these properties to specify which kinds of files to display in a file list box, based on standard file attributes used in the operating environment. Setting any of these properties with code at run time resets the list to display only those files with the corresponding attributes.

For example, in an application with restricted levels of access, you might want to display only read-only files by setting ReadOnly to True, and the other properties to False. Or, as part of a file backup procedure, you might set the Archive property to True to list only those files modified since the previous backup.

Data Type

Integer (Boolean)


See Also

Help:

Path Property

Pattern Property

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


BorderStyle Property

See Also

Applies To

Form, grid, image, label, line, OLE client, picture box, shape, text box.

Description

Determines the border style for an object.  For forms and text boxes, read-only at run time.

Usage

[form.][control.]BorderStyle

Setting

The BorderStyle property settings for a form are:

Setting	Description

0	None (no border or related border elements).

1	Fixed Single.  Can include Control-menu box, title bar, Maximize button, and Minimize button.  Resizable only using Maximize and Minimize buttons.

2	(Default) Sizable.  Resizable using any of the optional border elements listed for setting 1.

3	Fixed Double.  Can include Control-menu box and title bar; cannot include Maximize or Minimize buttons.  Not resizable.

The BorderStyle property settings for a grid, image, label, text box, OLE client, and picture box are:

Setting	Description

0	(Default for label and image) None.

1	(Default for picture box and text box) Fixed Single.

The BorderStyle property settings for a shape and a line 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 Double) is useful for standard dialog boxes.

In a form with BackStyle set to of 0 (None), there is no title bar or borders.  If such a form is inside an MDI form, any controls in the child form appear as if they are in the MDI form unless the two forms have differing BackColor settings.

MDI child forms with a setting of 2 (Sizable) will appear within the MDI form in a default size defined by Windows at run time.  For any other setting, the form will appear in the size you specify at design time.

Note	Setting 3 (Fixed Double) borders for forms are incompatible with menus.  A form with a menu and a Fixed Double border setting will appear with a Setting 1 (Fixed Single) border instead.

At run time, a form is either modal or modeless.  Use the Show method to specify whether a form appears as modal or modeless.

Data Type

Integer (Enumerated)


See Also

Help:

Caption Property

ControlBox Property

DrawStyle Property

MaxButton Property

MinButton Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Cancel Property

See Also

Applies To

Command button.

Description

Determines whether a command button is the Cancel button on a form.

Usage

[form.]commandbutton.Cancel[ = boolean ]

Setting

The Cancel property settings are:

Setting	Description

True	The command button is the Cancel button.

False	(Default) The command button isn't a Cancel button.

Remarks

Use the Cancel property to give a user the option of canceling uncommitted changes and returning the form to its previous state.

Only one command button on a form can be the Cancel button.  When the Cancel property is set to True for one command button, it is automatically set to False for all other command buttons on the form.  When the command button's Cancel property setting is True and the form is the active form, the user can choose the command button by clicking it, pressing the Esc key, or pressing Enter when the button has the focus.

Tip	For a form that supports irreversible operations, such as deletions, it's a good idea to make the Cancel button the default button.  To do this, set both the Cancel property and the Default property to True.

Data Type

Integer (Boolean)


See Also

Help:

Default Property

KeyDown, KeyUp Events

KeyPress Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Caption Property

See Also	Example

Applies To

Form, MDI form, check box, command button, frame, label, menu, option button.

Description

Form [image] determines the text displayed in the form's title bar.  When the form is minimized, this text is displayed below the form's icon.

Controls [image] determines the text displayed in or next to a control.

Usage

[form.][control.]Caption[ = stringexpression ]

Remarks

When you create a new object, its default caption is the same as the default Name for both forms and controls.  This default caption includes the object name and an integer, such as Command1 or Form1.  For a more descriptive label, set the Caption property.

You can use the Caption property to assign an access key to a control.  In the caption, include an ampersand (&) immediately preceding the character you want for an access key.  The character will be underlined.  Press Alt plus the underlined character to move the focus to that control.  To include an ampersand in a caption without creating an access key, type a double ampersand (&&).  A single ampersand will appear in the caption and no characters will be underlined.

For labels, the Caption is limited to 2048 characters.  For forms and all other controls that have captions, the limit is 255 characters.

To display a form caption, set the BorderStyle property to either 1, 2, or 3.  A caption too long for the form's title bar will be clipped.

When an MDI child form is maximized within an MDI form, the child form's caption is included with the parent form's caption.

Note	For a label, set the AutoSize property to True to automatically resize the control to fit its caption.

Data Type

String


See Also

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Caption Property Example

The example changes the caption on the command button each time the user clicks the button.  To try this example, paste the code into the Declarations section of a form containing a command button named Command1.  Then press F5 and click the form.

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

See Also	Example

Applies To

Menu.

Description

Determines whether a check mark is displayed next to a menu command.

Usage

menuitem.Checked[ = boolean ]

Setting

The Checked property settings are:

Setting	Description

True	Places a check mark next to a menu command.

False	(Default) Removes a check mark from a menu command.

Remarks

You can use code to set the Checked property at run time [image] for example, as part of a Click event procedure attached to a menu control.  You might also set the value of this property in a startup procedure or in a form's Load event procedure.

Data Type

Integer (Boolean)


See Also

Help:

Creating a Menu Bar

Enabled Property

Visible Property

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Checked Property Example

The example displays and removes a check mark next to a menu item.  To try this example, create a form with a menu having one command (set both Caption and Name = "MyMenuItem"). Then Press F5 and choose the menu item.

Sub MyMenuItem_Click ()

' Turn check mark on menu command on and off.

MyMenuItem.Checked = Not MyMenuItem.Checked

End Sub


ControlBox Property

See Also

Applies To

Form.

Description

Specifies whether a Control-menu box appears on a form at run time; read-only at run time.

Usage

[form.]ControlBox

Setting

The ControlBox property settings are:

Setting	Description

True	(Default) Displays the Control-menu box.

False	Removes the Control-menu box.

Remarks

To display a Control-menu box, you must also set the form's BorderStyle property to 1 (Fixed Single), 2 (Sizable), or 3 (Fixed Double).

Both modal and modeless windows can include a Control-menu box.  The commands available at run time depend on the settings for related properties [image] for example, setting MaxButton and MinButton to False disables the Maximize and Minimize commands on the Control menu, but the Move and Close commands remain available.

In Microsoft Windows version 3.0, an MDI child form appears with a Control-menu box regardless of the ControlBox setting.  However, if ControlBox is False, the menu appears without Close or Next commands.

Note	Settings you specify for ControlBox, BorderStyle, MaxButton, and MinButton are not reflected in the form's appearance until run time.

Data Type

Integer (Boolean)


See Also

Help:

BorderStyle Property

MaxButton Property

MinButton Property

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


DragIcon Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Determines the icon to be displayed as the pointer in a drag-and-drop operation.

Usage

[form.]control.DragIcon[ = icon ]

Where icon is any code that returns a valid icon, such as a reference to a form's icon (Form1.Icon), a reference to another control's DragIcon property (Text1.DragIcon), or the LoadPicture function.

Setting

The DragIcon property settings are:

Setting	Description

(none)	(Default) An arrow pointer inside a rectangle.

Icon	A custom mouse pointer.  You specify the icon by loading it using the Properties window at design time.  You can also use the LoadPicture function at run time.  The file you load must have the .ICO file-name extension and format.

Remarks

DragIcon is useful for providing visual feedback during a dragging operation [image] for example, to indicate that the source control is over an appropriate target.  DragIcon takes effect when the user initiates dragging.  Typically, you set DragIcon as part of a MouseDown or DragOver event procedure.

Note	At run time, the DragIcon property can be set to any object's DragIcon or Icon property, or you can assign it an icon returned by the LoadPicture function.

Data Type

Integer


See Also

Help:

Drag Method

DragDrop Event

DragMode Property

LoadPicture Function

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"

Appendix B, "Icon Library"


DragIcon Property Example

The example changes the drag icon each time you drag a picture control.  To try this example, paste the code into the Declarations section of a form that contains a picture control.  Set DragMode = 1. Then press F5 and click and drag the picture control.

Sub Form_DragDrop (Source As Control, X As Single, Y As Single)

Dim Pic	' Declare variable.

Source.Move X, Y	' Set position of control.

Pic = "icons\office\crdfle01.ico"	' Get name of icon file.

If Source.DragIcon = False Then	' If no picture loaded.

Source.DragIcon = LoadPicture(Pic)' Load picture.

Else

Source.DragIcon = LoadPicture()	' Unload picture.

End If

End Sub


DragMode Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Determines manual or automatic dragging mode for a drag-and-drop operation.

Usage

[form.]control.DragMode[ = mode ]

Setting

The DragMode property settings are:

Setting	Description

0	(Default) Manual; requires using the Drag method to initiate dragging on the source control.

1	Automatic; clicking the source control automatically initiates dragging.

Remarks

When DragMode is set to 1 (Automatic), the control does not respond as usual to mouse input messages.  Use the 0 (Manual) setting to determine when dragging begins or ends; this is useful for initiating dragging in response to a keyboard or menu command, or for allowing a source control to recognize a MouseDown event prior to dragging.

Clicking while the mouse pointer is over a target control or form during a drag operation generates a DragDrop event for the target object.  This ends the drag operation.  Dragging may also generate a DragOver event.

Note	While a control is being dragged, it cannot recognize other user-initiated mouse or keyboard events (KeyDown, KeyPress or KeyUp, MouseDown, MouseMove, or MouseUp).  However, the control can receive events initiated by code or by a DDE link.

Data Type

Integer (Enumerated)


See Also

Help:

DragDrop Event

DragIcon Property

DragOver Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DragMode Property Example

This example enables and disables the ability to drag a command button each time a form is clicked.  To try this example, paste the code into the Declarations section of a form that contains a command button.  Then press F5 and click the form.

Sub Form_Click ()

If Command1.DragMode = 0 Then	' Check DragMode.

Command1.DragMode = 1	' Turn it on.

Else

Command1.DragMode = 0	' Or turn if off.

End If

End Sub


DrawMode Property

See Also	Example

Applies To

Form, line, picture box, Printer object, shape.

Description

Determines the appearance of output from graphics methods, or the appearance of a shape or line control.

Usage

{[form.][control.]|Printer.}DrawMode[ = mode ]

Setting

The DrawMode property settings are:

Setting	Description

1	Black Pen.

2	Inverse of setting 15 (Merge Pen) [image] NotMergePen.

3	Combination of the colors common to the background color and the inverse of the pen [image] Mask Not Pen.

4	Inverse of setting 13 (Copy Pen) [image] NotCopyPen.

5	Combination of the colors common to both the pen and the inverse of the display [image] MaskPenNot.

6	Inverse of the display color [image] Invert.

7	Combination of the colors in the pen and in the display color, but not in both [image] XorPen.

8	Inverse of setting 9 (Mask Pen) [image] NotMaskPen.

9	Combination of the colors common to both the pen and the display [image] MaskPen.

10	Inverse of setting 7 (Xor Pen) [image] NotXorPen.

11	No operation [image] output remains unchanged.  In effect, this setting turns drawing off [image] Nop.

12	Combination of the display color and the inverse of the pen color [image] MergeNotPen.

13	(Default) Color specified by the ForeColor property [image] CopyPen.

14	Combination of the pen color and the inverse of the display color [image] MergePenNot.

15	Combination of the pen color and the display color [image] MergePen.

16	White Pen.

Remarks

Use this property to produce visual effects with shape or line controls or when drawing with the graphics methods.  Visual Basic compares each pixel in the draw pattern to the corresponding pixel in the existing background, and then it applies bitwise operations.  For example, setting 7 (Xor Pen) uses the Xor operator to combine a draw pattern pixel with a background pixel.

The exact effect of a DrawMode setting depends on the way the color of a line drawn at run time combines with colors already on the screen.  Settings 1, 6, 7, 11, 13, and 16 yield perhaps the most predictable results.

Data Type

Integer (Enumerated)


See Also

Help:

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


DrawMode Property Example

The example enables drawing on a form by dragging the mouse pointer.  Each mouse click sets a different draw mode.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Load

DrawWidth = 10	' Set DrawWidth.

End Sub

Sub Form_Click ()

Static M As Integer	' Current DrawMode setting.

ForeColor = QBColor(Int(Rnd * 15))	' Choose a color.

M = ((M + 1) Mod 16) + 1	' Keep DrawMode 16 or less.

DrawMode = M	' Set DrawMode.

End Sub

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

If Button Then	' While the button is pressed,

PSet (X, Y)	' draw a big point.

End If

End Sub


DrawStyle Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Determines the line style for output from graphics methods.

Usage

{[form.][picturebox.]|Printer.}DrawStyle[ = style ]

Setting

The DrawStyle property settings are:

Setting	Description

0	(Default) Solid

1	Dash

2	Dot

3	Dash-dot

4	Dash-dot-dot

5	Invisible

6	Inside solid

Remarks

If DrawWidth is set to a value greater than 1, then DrawStyles 1 through 4 produce a solid line (the DrawStyle property value is not changed).  If DrawWidth is set to 1, DrawStyle produces the effect described above for each setting.

Data Type

Integer (Enumerated)


See Also

Help:

Circle Method

DrawMode Property

FillColor Property

FillStyle Property

ForeColor Property

Line Method

PSet Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


DrawStyle Property Example

The example draws seven lines across a form, with each line displaying a different DrawStyle.  (If you set AutoRedraw = True, the form accumulates a new set of lines each time you resize it and then click it.)  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

ScaleHeight = 8	' Divide height by 8.

For I = 0 To 6

DrawStyle = I	' Change style.

Line (0, I + 1) - (ScaleWidth, I + 1)	' Draw new line.

Next I

End Sub


DrawWidth Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Determines the line width for output from graphics methods.

Usage

{[form.][picturebox.]|Printer.}DrawWidth[ = size ]

Setting

You can set DrawWidth to a value of 1 through 32,767.  This value represents the width of the line in pixels.  The default is 1, or 1 pixel wide.

Remarks

Increase the value of this property to increase the width of the line.  If DrawWidth is greater than 1, DrawStyle property settings 1 through 4 produce a solid line (the DrawStyle property value isn't changed).  Setting DrawWidth to 1 allows DrawStyle to produce the results shown in the DrawStyle property table.

Data Type

Integer


See Also

Help:

Circle Method

DrawMode Property

DrawStyle Property

FillColor Property

FillStyle Property

ForeColor Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


DrawWidth Property Example

The example draws a gradually thickening line across a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

DrawWidth = 1	' Set starting pen width.

PSet (0, ScaleHeight / 2)	' Set starting point.

ForeColor = QBColor(5)' Set pen color.

For I = 1 To 100 Step 10	' Set up loop.

DrawWidth = I	' Reset pen width.

Line - Step(ScaleWidth / 10, 0)	' Draw a line.

Next I

End Sub


Drive Property

See Also	Example

Applies To

Drive list box.

Description

Determines the selected drive at run time; not available at design time.

Usage

drivelistbox.Drive[ = drivespec]

Remarks

The valid range for the Drive property includes all drives present in or connected to the system when the control is created or refreshed at run time.  The Drive property defaults to the current drive.

When reading this property, the selected drive is returned in one of the following formats:

Floppy disks [image] "a:" or "b:", and so on.

Fixed media [image] "c: [volume id]"

Network connections [image] "x: \\server\share"

When setting this property:

Only the first character of the string is significant (the string is not case-sensitive).

Changing the setting for Drive causes a Change event.

Selecting a drive that is not present causes an error.

Setting this property also regenerates the drive list, providing a way in code to track network connections added since the control was created.

If the FileName property is set to a qualified network path without a drive designation, the value of the Drive property is an empty string (""), no drive is selected, and the ListIndex property is -1.

Note	The Drive property returns a different value from the ListIndex, which returns the list box selection.

Data Type

String


See Also

Help:

FileName Property

Path Property

PathChange Event

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Drive Property Example

The example displays a list of files for the current drive and directory.  To try this example, paste the code into the Declarations section of a form that contains a drive list box, a directory list box and a file list box..  Then press F5.  Use the mouse to change the drive or directory.

Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' When Drive changes, set Dir path.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' When Dir changes, set File path.

End Sub


Enabled Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, menu, option button, picture box, text box, timer, vertical scroll bar.

Description

Determines whether the form or control can respond to user-generated events.

Usage

[form.][control.]Enabled[ = boolean ]

Setting

The Enabled property settings are:

Setting	Description

True	(Default) Allows the object to respond to events.

False	Prevents the object from responding to events.

Remarks

This property allows forms and controls to be enabled or disabled at run time.  For example, you can disable objects that don't apply to the current state of the application.  You can also disable a control used purely for display purposes, such as a text box that provides read-only information.

Disabling a timer by setting Enabled to False suspends the countdown set up by the control's Interval property.

Data Type

Integer (Boolean)


See Also

Help:

Interval Property

Visible Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Enabled Property Example

The example enables a command button whenever the text box contains text.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and type something into the text box.

Sub Form_Load ()

Text1.Text = ""	' Clear the text box.

Command1.Caption = "Save"	' Put caption on button.

End Sub

Sub Text1_Change ()

If Text1.Text = "" Then	' See if textbox is empty.

Command1.Enabled = False	' Disable button.

Else

Command1.Enabled = True	' Enable button.

End If

End Sub


FileName Property

See Also	Example

Applies To

File list box.

Description

Determines the selected file in the list portion of a file list box.  Not available at design time.

Usage

[form.]filelistbox.FileName[ = filename ]

Remarks

The FileName property is set to a null string (""), meaning no currently selected file, when the control is created at run time.

Reading this property returns the currently selected file name from the list.  The path is retrieved separately, using the Path property.  The value is functionally equivalent to List(ListIndex).  If no file is selected, FileName returns a null string ("").

When setting this property:

Including a drive, path, or pattern in the string changes the Drive, Path, and Pattern properties accordingly.

Including the name of an existing file (without wildcard characters) in the string selects the file.

Changing the value of this property may also cause one or more of these events:  PathChange (if you change the path); PatternChange (if you change the pattern); or DblClick (if you've assigned an existing file name).

This property can be a qualified network path and filename using this syntax: \\servername\sharename\filename.

Data Type

String


See Also

Help:

Drive Property

List Property

ListIndex Property

Path Property

PathChange Event

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


FileName Property Example

The example displays a message in a label when a file name in a file list box is double-clicked.  To try this example, paste the code into the Declarations section of a form that contains a label, a directory list box, and a file list box..  Then press F5 and double click any filename in the file list box.

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set File1 path.

End Sub

Sub File1_PathChange ()

Dir1.Path = File1.Path	' Set Dir1 path.

End Sub

Sub File1_DblClick ()

' Display the selected filename when DblClicked.

Label1.Caption = "Your selection: " + UCase(File1.FileName)

End Sub


FillColor Property

See Also	Example

Applies To

Form, picture box, Printer object, shape.

Description

Determines the color used to fill in shapes; also used to fill in circles and boxes created with the Circle and Line graphics methods.

Usage

{[form.][control.]|Printer.}FillColor[ = color ]

Setting

The FillColor property settings are:

Setting	Description

Normal RGB colors	Colors set with the RGB or QBColor functions in code.

System default colors	Colors specified with the system color constants from CONSTANT.TXT, a Visual Basic file that you can load into a module.  The Windows environment substitutes the user's choices, as specified through the user's Control Panel settings.

By default, FillColor is set to 0 (black).

Remarks

When the FillStyle property is set to its default, 1 (Transparent), the FillColor setting is ignored.

Data Type

Long


See Also

Help:

BackColor, ForeColor Properties

FillStyle Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


FillColor Property Example

The example constructs a circle on your form with random FillColors and FillStyles as you click your mouse button.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

FillColor = QBColor(Int(Rnd * 15))	' Choose random FillColor.

FillStyle = Int(Rnd * 8)	' Choose random FillStyle.

Circle (X, Y), 250	' Draw a circle.

End Sub


FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

See Also	Example

Apply To

Form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, label, list box, option button, picture box, Printer object, text box.

Description

Determine font styles in the following formats:  FontBold, FontItalic, FontStrikethru, and FontUnderline.  FontTransparent determines whether background text or graphics are included with the characters in a particular font; this property applies only to forms, picture boxes, and the Printer object.

Usage

{[form.][control.]|Printer.}FontBold[ = boolean ]

{[form.][control.]|Printer.}FontItalic[ = boolean ]

{[form.][control.]|Printer.}FontStrikethru[ = boolean ]

{[form.][picturebox.]|Printer.}FontTransparent[ = boolean ]

{[form.][control.]|Printer.}FontUnderline[ = boolean ]

Setting

The settings for the FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties are:

Setting	Description

True	(Default for FontBold and FontTransparent) Turns on the formatting in that style.  Setting FontTransparent to True permits background graphics or text to show through the characters in a font.

False	(Default for FontItalic, FontStrikethru, and FontUnderline) Turns off the formatting in that style.  Setting FontTransparent to False masks out existing background graphics or text.

Remarks

Use these font properties to format text, either at design time using the Properties window or at run time using code.  For forms, picture boxes, and the Printer object, setting these properties does not affect graphics or print output already drawn to a form, picture box, or Printer object.  For all other controls, font changes take effect on the screen immediately.

Note	Fonts available in Visual Basic vary according to your system configuration, display devices, and printing devices.  Font-related properties can be set only to values for which actual fonts exist.

In general, you should change the FontName property before setting size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties.  One exception to this is when you need to set TrueType fonts to smaller than 8 points.  In this case, you should set the point size with the FontSize property, then set the FontName property, and finally, set the size again with the FontSize property.  The Windows environment actually uses a different font for TrueType fonts that are smaller than 8 points.

Data Type

Integer (Boolean)


See Also

Help:

TextHeight Method

TextWidth Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties Example

The example puts text on a form in one of two different combinations of styles with each mouse click.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

FontStrikethru = Not FontStrikethru	' Set strikethru.

FontItalic = Not FontStrikethru	' Set font style.

Print "Now is the time!"	' Print some text.

End Sub


FontCount Property

See Also	Example

Applies To

Printer object, Screen object.

Description

Specifies the number of fonts available for the current display device or currently active printer; not available at design time and read-only at run time.

Usage

{Printer|Screen}.FontCount

Remarks

Use this property with the Fonts property to see a list of available screen or printer fonts.  Fonts available in Visual Basic vary according to your system configuration, display devices, and printing devices.

Data Type

Integer


See Also

Help:

FontName Property

Fonts Property

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontCount Property Example

The example prints a list of the printer fonts in a list box.  To try this example, paste the code into the Declarations section of a form that has a list box control named List1.  Then Press F5  and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

For I = 0 To Printer.FontCount -1	' Determine number of fonts.

List1.AddItem Printer.Fonts (I)	' Put each font into list box.

Next I

End Sub


hDC Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Specifies a handle provided by the Windows environment  to the device context of an object; not available at design time and read-only at run time.

Usage

{[form.][picturebox.]|Printer.}hDC

Remarks

This property is a Microsoft Windows environment device context handle.  The Windows environment manages the system display by assigning a device context for the Printer object and for each form and picture box in your application.  You can refer to the handle for an object's device context with the hDC property, which provides a value to pass to Windows API calls.

Note	The value of the hDC property can change while a program is running.  Therefore, you should not store the value in a variable; instead, use the hDC property each time you need it.

The AutoRedraw property can cause hDC to change.  If AutoRedraw for a form or picture box is set to True, hDC acts as a handle to the device context of the persistent bitmap (equivalent to the Image property).  When AutoRedraw is False, hDC is the actual hDC value of the Form window and the picture box window.  Note that hDC may change while the program is running regardless of the AutoRedraw setting.

Data Type

Integer


See Also

Help:

hWnd Property

Icon Property

Programmer's Guide:

Chapter 22, "Calling Procedures in DLLs"


hDC Property Example

The example draws a triangle, and then uses a Windows function to fill it with color.  Be sure that the declaration appears on one line with no break or wordwrap in the form module.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

' Declaration of Windows routine.

Declare Sub FloodFill Lib "GDI" (ByVal hDC As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal Color As Long)

Sub Form_Click ()

ScaleMode = 3	' Windows draws in pixels.

ForeColor = 0	' Set draw line to black.

Line (100, 50)-(300, 50)	' Draw a triangle.

Line -(200, 200)

Line -(100, 50)

FillStyle = 0	' Set FillStyle to solid.

FillColor = RGB(128, 128, 255)	' Set FillColor.

FloodFill hDC, 200, 100, ForeColor	' Call Windows API to fill.

End Sub


Icon Property

See Also	Example

Applies To

Form, MDI form.

Description

Determines the icon displayed for a form at run time when the form is minimized.

Usage

[form.]Icon

Remarks

Use this property to specify a custom icon for any form that the user can minimize at run time.  For example, you can assign a unique icon to a form to indicate the form's function.  Specify the icon by loading it using the Properties window at design time.  The file you load must have the .ICO file-name extension and format.  If you don't specify a custom icon, the Visual Basic default icon for forms will be used.

You can use Visual Basic's Icon Library (in the ICONS subdirectory) as a source for icons.  When you create an executable file, you can assign an icon to the application by using the Icon property of any form in that application.

Note	To see a form's icon, the form must be minimized.  The BorderStyle property must be set to either 1 (Fixed Single) or 2 (Sizable).  The MinButton property must be set to True.

At run time, you can assign an object's Icon property to another object's DragIcon or Icon property.  You can also assign an icon returned by the LoadPicture function.  Using LoadPicture with no argument assigns an empty (null) icon to the form, which enables you to draw on the icon at run time.

Data Type

Integer


See Also

Help:

Assigning an Icon to a Form

LoadPicture Function

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Appendix B, "Icon Library"


Icon Property Example

The example creates a blank icon for a form and draws colored dots on the icon as long as the form is minimized.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and minimize the form.

Sub Form_Resize ()

Dim X, Y	' Declare variables.

If Form1.WindowState = 1 Then

Form1.Icon = LoadPicture()	' Load a blank icon.

Do While Form1.WindowState = 1	' While form is minimized.

Form1.DrawWidth = 10	' Set size of dot.

' Choose random color for dot

Form1.ForeColor = QBColor(Int(Rnd * 15))

' Set random location on icon

X = Form1.Width * Rnd

Y = Form1.Height * Rnd

PSet (X, Y)	' Draw dot on icon.

DoEvents	' Allow other events.

Loop

End If

End Sub


Interval Property

See Also	Example

Applies To

Timer.

Description

Determines the number of milliseconds between calls to a timer control's Timer event.

Usage

[form.]timer.Interval[ = milliseconds ]

Setting

The Interval property settings are:

Setting	Description

0	(Default) Disables a timer.

1 to 65,535 	Sets an interval (in milliseconds) that takes effect when a timer control's Enabled property is set to True.  Specify a long integer in this range.  For example, a value of 10,000 milliseconds equals 10 seconds.  The maximum, 65,535 milliseconds, is equivalent to just over one minute.

Remarks

You can set a timer control's Interval property at design time or run time.  When using the Interval property, remember:

The timer control's Enabled property determines whether the timer control responds to the passage of time.  Set Enabled to False to turn the timer off, and to True to turn it on.  When a timer is enabled, its countdown always starts from the value of its Interval property setting.

Write a Timer event procedure to tell Visual Basic what to do each time the Interval has passed.

Note	There are a limited number of timers available (16 in the Windows environment).  Trying to start a timer if none is available causes a run-time error.

Data Type

Long


See Also

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


Interval Property Example

The example allows you to adjust the speed at which a form switches colors.  To try this example, paste the code into the Declarations section of a form that contains a timer, a horizontal scroll bar, and a picture box.  Then press F5 and click the scroll bar.

Sub Form_Load ()

Timer1.Interval = 900	' Set interval.

HScroll1.Min = 100	' Set minimum.

HScroll1.Max = 900	' Set maximum.

End Sub

Sub HScroll1_Change ()

' Set interval according to scroll bar value.

Timer1.Interval = 1000 - HScroll1.Value

End Sub

Sub Timer1_Timer ()

' Switch BackColor between Red and Blue.

If Picture1.BackColor = RGB(255, 0, 0) Then

Picture1.BackColor = RGB(0, 0, 255)

Else

Picture1.BackColor = RGB(255, 0, 0)

End If

End Sub


LargeChange, SmallChange Properties

See Also	Example

Apply To

Horizontal scroll bar, vertical scroll bar.

Description

LargeChange [image] determines the amount of change to the Value property in a scroll bar control when the user clicks the area between the scroll box and scroll arrow.

SmallChange [image] determines the amount of change to the Value property in a scroll bar control when the user clicks a scroll arrow.

Usage

[form.]{hscrollbar|vscrollbar}.LargeChange[ = change ]

[form.]{hscrollbar|vscrollbar}.SmallChange[ = change ]

Remarks

For both properties, you can specify an integer between 1 and 32,767, inclusive.  By default, each property is set to 1.

The Windows environment automatically sets proportional scrolling increments for scroll bars on form windows, combo boxes, and list boxes based on the amount of data in the control.  For a scroll bar control, however, you must specify these increments.  Use LargeChange and SmallChange to set scrolling increments appropriate to how the scroll bar is being used.

Typically, you set LargeChange and SmallChange at design time.  You can also reset them in code at run time when the scrolling increment must change dynamically.

Note	You set the maximum and minimum ranges of a scroll bar control with the Max and Min properties.

Data Type

Integer


See Also

Help:

Change Event

Value Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


LargeChange, SmallChange, Max, Min Properties Example

The example uses a scroll bar to move a picture box control across the form.  To try this example, paste the code into the Declarations section of a form that contains a small picture box and a horizontal scroll bar.  Then press F5 and click the scroll bar.

Sub Form_Load ()

HScroll1.Max = 100	' Set maximum value.

HScroll1.LargeChange = 20	' Cross in 5 clicks.

HScroll1.SmallChange = 5	' Cross in 20 clicks.

Picture1.Left = 0	' Start picture at left.

Picture1.BackColor = QBColor(3)	' Set color of picture box.

End Sub

Sub HScroll1_Change ()

' Move picture according to scroll bar.

Picture1.Left = (HScroll1.Value / 100) * ScaleWidth

End Sub


Left, Top Properties

See Also	Example

Apply To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE client, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Left [image] determines the distance between the internal left edge of an object and the left edge of its container.

Top [image] determines the distance between the internal top edge of an object and the top edge of its container.

For a form, the Left and Top properties are always expressed in twips; for a control, they are measured in units according to the coordinate system of its container.  The values for these properties change as the object is moved by the user or by code.  For a timer, these properties are not available at run time.

Usage

[form.][control.]Left[ = x ]

[form.][control.]Top[ = y ]

Remarks

For both properties, you can specify a single-precision number.

Use Left and Top, and the Height and Width properties, for operations based on an object's external dimensions, such as moving or resizing.  Use the ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth properties for operations based on an object's internal dimensions, such as drawing or moving objects that are contained within the object.  The scale-related properties apply only to forms, picture boxes, and the Printer object.

Data Type

Single


See Also

Help:

Left Function

Move Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Left, Top Properties Example

The example sets the size of a form to 75% of screen size, and centers the form when it is loaded.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Width = Screen.Width * .75	' Set height of form.

Height = Screen.Height * .75	' Set width of form.

Left = (Screen.Width - Width) / 2	' Center form horizontally.

Top = (Screen.Height - Height) / 2	' Center form vertically.

End Sub


List Property

See Also	Example

Applies To

Combo box, directory list box, drive list box, file list box, list box.

Description

Determines the items contained in a control's list portion.  The list is a string array in which each element is a list item.  Not available at design-time; read-only at run time for a directory list box, drive list box, and file list box; read/write at run time for a combo box and list box.

Usage

[form.]control.List(index)[ = stringexpression ]

Remarks

Use this property to access list items.

For all controls except the directory list box, the index of the first item is 0 and the index of the last item is ListCount - 1.

For a directory list box, the index number sequence is based on the directories and subdirectories present when the control is created at run time.  The currently expanded directory is represented using the index -1.  Directories above the currently expanded directory are represented by negative indexes with higher absolute values.  For example, -2 is the parent directory of the currently expanded directory and -3 is the directory above that.  Directories below the currently expanded directory range from 0 to ListCount -1.

Initially, combo boxes and list boxes contain an empty list.  For the file-system controls, the list is based on conditions that exist when the control is created at run time:

Directory list box [image] contains a list of all directories, using the range -n to ListCount - 1.

Drive list box [image] contains the list of drive connections in effect.

File list box [image] contains the list of files in the currently expanded directory that match the Pattern property.  The path is not included.

The List property works in conjunction with the ListCount and ListIndex properties.

For all applicable controls except a directory list box, enumerating a list from 0 to ListCount -1 returns all items in the list.  For a directory list box, enumerating the list from -n to ListCount -1 returns a list containing all directories and subdirectories visible from the currently expanded directory.  In this case n is the number of directory levels above the currently expanded directory.

Note	To specify items you want to display in a combo box or list box, use the AddItem method.  To remove items, use the RemoveItem method.  To keep items in alphabetical order, set the control's Sorted property to True before adding items to the list.

Using an Option Base = 1 statement in the Declarations section does not affect the enumeration of elements in Visual Basic controls.  The first element is always 0.

When the List index is outside the range of actual entries in the list box, an empty string is returned.  For example, List(-1) returns an empty string for a combo box or list box.

Data Type

String array


See Also

Help:

ListCount Property

ListIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


List Property Example

The example loads a combo box with a list of sandwich names and displays the first item in the list.  To try this example, paste the code into the Declarations section of a form that contains a combo box.  Then press F5.

Sub Form_Load ()

Combo1.AddItem "Denver Sandwich"	' Add each item to list.

Combo1.AddItem "Reuben Sandwich"

Combo1.AddItem "Turkey Sandwich"

Combo1.Text = Combo1.List(0)	' Display first item.

End Sub


ListCount Property

See Also	Example

Applies To

Combo box, directory list box, drive list box, file list box, list box.

Description

Specifies the number of items in the list portion of a control; not available at design time and read-only at run time.

Usage

[form.]control.ListCount

Remarks

ListCount provides specific information for each control:

Combo box and list box [image] the number of items in the list.

Directory list box [image] the number of subdirectories in the current directory.

Drive list box [image] the number of drive connections.

File list box [image] the number of files in the current directory that match the Pattern property.

Data Type

Integer


See Also

Help:

AddItem Method

List Property

ListIndex Property

RemoveItem Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ListCount Property Example

The example loads a list of your printer fonts into a combo box, displays the first item in the list, and prints the total number of fonts.  Each click of the button changes all items in the list to uppercase or lowercase.  To try this example, paste the code into the Declarations section of a form that contains a combo box (Style = 2) and a command button.  Then press F5 and click the command button.

Sub Form_Load ()

Dim I	' Declare variable.

AutoRedraw = True	' Set AutoRedraw.

For I = 0 To Printer.FontCount - 1	' Put font names in list.

Combo1.AddItem Printer.Fonts(I)

Next I

Combo1.ListIndex = 0	' Set text to first item.

' Print ListCount info on form.

Print "Number of Printer fonts: "; Combo1.ListCount

End Sub

Sub Command1_Click ()

Static UpperCase

Dim I	' Declare variable

For I = 0 To Combo1.ListCount - 1	' Loop through list.

If UpperCase Then

Combo1.List(I) = UCase(Combo1.List(I))

Else

Combo1.List(I) = LCase(Combo1.List(I))

End If

Next I

UpperCase = Not UpperCase' Change case.

End Sub


ListIndex Property

See Also	Example

Applies To

Combo box, directory list box, drive list box, file list box, list box.

Description

Determines the index of the currently selected item in the control.  Not available at design time.

Usage

[form.]control.ListIndex[ = index ]

Setting

The ListIndex property settings are:

Setting	Description

-1	(Default for combo box, directory list box, and drive list box) Indicates no item is currently selected.  For a combo box, indicates the user has entered new text into the text box portion of the combo box.  For a directory list box, indicates the index of the current path.  For a drive list box, indicates the index of the current drive when the control is created at run time.

n	(Default for file list box and list box) A number indicating the index of the currently selected item.

Remarks

The expression List(List1.ListIndex) returns the string for the currently selected item.

Data Type

Integer


See Also:

Help:

AddItem Method

Drive Property

List Property

ListCount Property

Path Property

RemoveItem Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ListIndex Property Example

The example displays the names of three players in a list box and the corresponding salary of the selected player in a label.  To try this example, paste the code into the Declarations section of a form that contains a combo box and a label.  Then press F5 and choose a name from the combo box.

' General declarations

Dim Player(0 To 2)	' Dimension two arrays.

Dim Salary(0 To 2)

Sub Form_Load ()

Dim I	' Declare variable.

AutoSize = True

Player(0) = "Miggey McMoo"	' Enter data into arrays.

Player(1) = "Alf Hinshaw"

Player(2) = "Woofer Dean"

Salary(0) = "$234,500"

Salary(1) = "$158,900"

Salary(2) = "$1,030,500"

For I = 0 To 2	' Add names to list.

Combo1.AddItem Player(I)

Next I

Combo1.ListIndex = 0	' Display first item in list.

End Sub

Sub Combo1_Click ()

' Display corresponding salary for name.

Label1.Caption = Salary(Combo1.ListIndex)

End Sub


Max, Min Properties

See Also	Example

Apply To

Horizontal scroll bar, vertical scroll bar.

Description

Max [image] determines a scroll bar position's maximum Value property setting when the scroll box is in its bottommost position (vertical scroll bar) or rightmost position (horizontal scroll bar).

Min [image] determines a scroll bar position's minimum Value property setting when the scroll box is in its topmost position (vertical scroll bar) or leftmost position (horizontal scroll bar).

Usage

[form.]{hscrollbar|vscrollbar}.Max[ = limit ]

[form.]{hscrollbar|vscrollbar}.Min[ = limit ]

Setting

For each property, you can specify an integer between -32,768 to 32,767, inclusive.  The default settings are:

Max [image] 32,767.

Min [image] 0.

Remarks

The Windows environment automatically sets ranges for scroll bars proportional to the contents of forms, combo boxes, and list boxes.  For a scroll bar control, however, you must specify these ranges.  Use Max and Min to set a range appropriate to how the scroll bar control is used [image] for example, as an input device or as an indicator of speed or quantity.

Typically, you set Max and Min at design time.  You can also set them in code at run time if the scrolling range must change dynamically [image] for example, when adding records to a database that can be browsed with a scroll bar.  You set the maximum and minimum scrolling increments for a scroll bar control with the LargeChange and SmallChange properties.

Note	If Max is set to less than Min, the maximum value is then set at the leftmost or topmost position of a horizontal or vertical scroll bar, respectively.

Data Type

Integer


See Also

Help:

LargeChange, SmallChange Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


MaxButton Property

See Also

Applies To

Form.

Description

Specifies whether a form has a Maximize button; read-only at run time.

Usage

[form.]MaxButton

Setting

The MaxButton property settings are:

Setting	Description

True	(Default) The form has a Maximize button.

False	The form does not have a Maximize button.

Remarks

A Maximize button enables users to enlarge a form window to full-screen size.  To display a Maximize button, you must also set the form's BorderStyle property to either 1 (Fixed Single) or 2 (Sizable).

A Maximize button automatically becomes a Restore button when a window is maximized.  Minimizing or restoring a window automatically changes the Restore button back to a Maximize button.

The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox are not reflected in the form's appearance until run time.

In Microsoft Windows version 3.0, an MDI child form appears with a Maximize button regardless of the MaxButton setting.  However, if MaxButton is False, the Maximize button does not respond to mouse clicks and the Maximize command is not on the form's Control-menu box.

Note	Maximizing a form at run time generates a Resize event.  The WindowState property reflects the current state of the window.  If you set the WindowState property to 2 (Maximized), the form is maximized independently of whatever settings are in effect for the MaxButton and BorderStyle properties.

Data Type

Integer (Boolean)


See Also

Help:

ControlBox Property

MinButton Property


MinButton Property

See Also

Applies To

Form.

Description

Specifies whether a form has a Minimize button; read-only at run time.

Usage

[form.]MinButton

Setting

The MinButton property settings are:

Setting	Description

True	(Default) The form has a Minimize button.

False	The form does not have a Minimize button.

Remarks

A Minimize button enables users to shrink a form window to an icon.  To display a Minimize button, you must also set the form's BorderStyle property to either 1 (Fixed Single) or 2 (Sizable).

The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox are not reflected in the form's appearance until run time.

In Microsoft Windows version 3.0, an MDI child form appears with a Mimimize button regardless of the MinButton setting.  However, if MinButton is False, it does not respond to mouse clicks and the Minimize command is not on the form's Control-menu box.

Note	Shrinking a form to an icon at run time generates a Resize event.  The WindowState property reflects the current state of the window.  If you set the WindowState property to 2 (Maximized), the form is maximized independently of whatever settings are in effect for the MaxButton and BorderStyle properties.

Data Type

Integer (Boolean)


See Also

Help:

Assigning an Icon to a Form

ControlBox Property

MaxButton Property


Page Property

See Also	Example

Applies To

Printer object.

Description

Specifies the current page number.  Not available at design time and read-only at run time.

Usage

Printer.Page

Remarks

Visual Basic keeps a count of pages that have been printed since your application started or since the last Printer.EndDoc statement was executed.  This count starts at one and increases by one if:

You use the NewPage method.

You use the Print method and the text you wish to print does not fit on the current page.

Note	Graphics methods output that does not fit on the page does not generate a new page.  The output is clipped to fit the page's printable area.

Data Type

Integer


See Also

Help:

EndDoc Method

NewPage Method

Print Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Page Property Example

The example prints three pages of text with the current page number at the top.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Header, I, Y	' Declare variables.

Print "Now printing..."	' Put notice on form.

Header = "Printing Demo - Page "	' Set header string.

For I = 1 To 3

Printer.Print Header;	' Print header.

Printer.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.Page	' Print page number.

Next

Printer.NewPage

Next I

Printer.EndDoc

End

End Sub


Path Property

See Also	Example

Applies To

App object, directory list box, file list box.

Description

Determines the current absolute path, including the drive name.  Not available at design time.  For the App object, read-only at run time.

Usage

[form.]{dirlistbox|filelistbox}.Path[ = spec ]

App.Path

Setting

The value of the Path property is a string indicating a path, such as "C:\VB" or "C:\WINDOWS\SYSTEM."  For a directory list box or a file list box, the default is the current path when the control is created at run time.  For the App object, Path specifies the absolute path of the project when running the application from the development environment, and the absolute path of the .EXE file when running the application as an executable file.

Remarks

Use this property when building an application's file-browsing and manipulation capabilities.  Setting the Path property has effects on the control similar to the MS-DOS chdir command [image] relative paths are allowed with or without a drive.  Setting only a drive (with colon) selects the current directory on that drive.

This property can also be set to a qualified network path without a drive connection using the following syntax:

\\servername\sharename\path

which changes the Drive property to an empty string ("").

Changing the value of Path has these effects:

For a directory list box, generates a Change event.

For a file list box, generates a PathChange event.

Note	For a directory list box, the return value of Path is different from that of List(ListIndex), which returns only the selection.

Data Type

String


See Also

Help:

Archive, Hidden, Normal, ReadOnly, System Properties

Drive Property

FileName Property

List Property

ListCount Property

ListIndex Property

PathChange Event

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Path Property Example

The example displays a list of files for the selected drive and directory.  To try this example, paste the code into the Declarations section of a form that contains a drive list box, a directory list box, and a file list box.  Then press F5.  Use the mouse to change the drive or directory.

Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' Set Dir path.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set File path.

End Sub


Pattern Property

See Also	Example

Applies To

File list box.

Description

Determines which file names are displayed in a file list box at run time.

Usage

[form.]filelistbox.Pattern[ = display ]

Setting

The value of the Pattern property is a string indicating a file specification, such as "*.*" or "*.FRM".  The default is "*.*", which returns a list of all files.  In addition to using wildcard characters, you can also use multiple patterns separated by semicolons.  For example, "*.EXE; *.BAT" would return a list of all executable files and all MS-DOS batch files.

Remarks

The Pattern property plays a key role in designing an application's file-browsing and manipulation capabilities.  Use Pattern in combination with other file-control properties to provide the user with ways to explore files or groups of similar files.  For example, in an application dedicated to launching other programs, you might designate that only .EXE files be displayed in the file list box (*.EXE).  Other key file-control properties include Drive, FileName, and Path.

Changing the value of Pattern generates a PatternChange event.

Data Type

String


See Also

Help:

Archive, Hidden, Normal, ReadOnly, System Properties

Path Property

PathChange Event

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Pattern Property Example

The example updates a text box with the new pattern selected in a file list box.  The controls are set up so that when the user enters a pattern in the text box, such as *.TXT, it is reflected in the file list box, much like the interaction you see in a typical File Open dialog box in an application for Microsoft Windows.  If a full path such as C:\BIN\*.EXE is entered into the text box, the text is automatically parsed into path and pattern components by the file list box.  To try this example, paste the code into the Declarations section of a form that contains a directory list box, a file list box, a text box, and a command button.  Then press F5 and type a valid file pattern into the text box.

Sub Form_Load ()

Command1.Default = True	' Set Default property.

End Sub

Sub Command1_Click ()

' Text is parsed into path and pattern components.

File1.Filename = Text1.Text

Dir1.Path = File1.Path	' Set directory path.

End Sub

Sub File1_PatternChange ()

Text1.Text = File1.Pattern	' Set text to new pattern.

End Sub

Sub Dir1_Change

File1.Path = Dir1.Path	' Set file list box path.

End Sub


SelLength, SelStart, SelText Properties

See Also	Example1	Example2

Apply To

Combo box, text box.

Description

SelLength [image] determines the number of characters selected.

SelStart [image] determines the starting point of text selected; indicates the position of the insertion point if no text is selected.

SelText [image] determines the string containing the currently selected text; consists of an empty string ("") if no characters are selected.

These properties are not available at design time.

Usage

[form.]{combobox|textbox}.SelLength[ = length ]

[form.]{combobox|textbox}.SelStart[ = index ]

[form.]{combobox|textbox}.SelText[ = stringexpression ]

Setting

For SelLength and SelStart, the valid range of settings is 0 to text length [image] the total number of characters in the edit area of a combo box or text box.

Remarks

Use these properties for tasks such as setting the insertion point, establishing an insertion range, selecting substrings in a control, or clearing text.  Used in conjunction with the Clipboard object, these properties are useful for copy, cut, and paste operations.

When working with these properties:

Setting SelLength less than 0 causes a run-time error.

Setting SelStart greater than the text length sets the property to the existing text length; changing SelStart changes the selection to an insertion point and sets SelLength to 0.

Setting SelText to a new value sets SelLength to 0 and replaces the selected text with the new string.

Data Type

SelLength, SelStart [image] Long

SelText [image] String


See Also

Help:

ActiveControl Property

ActiveForm Property

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


SelLength, SelStart, SelText Properties Example 1

This example lets the user specify some text to search for, and then searches the text and selects it, if found.  To try this example, paste the code into the Declarations section of a form that contains a wide text box.  Then press F5 and click the form.

Sub Form_Load ()

Text1.Text = "Two of the peak human experiences"

Text1.Text = Text1.Text & " are good food and classical music."

End Sub

Sub Form_Click ()

Dim Search, Where	' Declare variables.

' Get search string from user.

Search = InputBox("Enter text to be found:")

Where = InStr(Text1.Text, Search)' Find string in text.

If Where Then	' If found...

Text1.SelStart = Where - 1' Set selection start.

Text1.SelLength = Len(Search)' Set selection length.

Else

MsgBox "String not found."	' Notify user

End If

End Sub


SelLength, SelStart, SelText Properties Example 2

This example shows how the Clipboard is used in cut, copy, paste, and delete operations.  To try this example, create a form with a text box and use the Menu Design window to create an Edit menu (for each of the commands, set Caption = Cut, Copy, Paste, and Delete; and set Name = EditCut, EditCopy, EditPaste, and EditDelete, respectively).

Sub EditCut_Click ()

' Copy selected text to Clipboard.

ClipBoard.SetText Screen.ActiveControl.SelText

' Delete selected text.

Screen.ActiveControl.SelText = ""

End Sub

Sub EditCopy_Click ()

' Copy selected text to Clipboard.

ClipBoard.SetText Screen.ActiveControl.SelText

End Sub

Sub EditPaste_Click ()

' Place text from Clipboard into active control.

Screen.ActiveControl.SelText = ClipBoard.GetText ()

End Sub

Sub EditDelete_Click ()

' Delete selected text.

Screen.ActiveControl.SelText = ""

End Sub


Sorted Property

See Also

Applies To

Combo box, list box.

Description

Specifies whether the elements of a combo box or list box are automatically sorted alphabetically; read-only at run time.

Usage

[form.]{combobox|listbox}.Sorted

Setting

The Sorted property settings are:

Setting	Description

True	List items are sorted alphabetically.

False	(Default) List items are not sorted alphabetically.

Remarks

When set to True, Visual Basic handles almost all necessary string processing to maintain alphabetical order, including changing the index numbers for items as required by the addition or removal of items.

Note	Using the AddItem method to add an element to a specific location in the list may violate the sort order, and subsequent additions may not be correctly sorted.

Data Type

Integer (Boolean)


See Also

Help:

AddItem Method

List Property

ListCount Property

ListIndex Property

RemoveItem Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Style Property

See Also

Applies To

Combo box.

Description

Specifies the type of combo box and the behavior of its list box portion; read-only at run time.

Usage

[form.]combobox.Style

Setting

The Style property settings are:

Setting	Description

0	(Default) Dropdown Combo.  Includes a drop-down list and an edit area.  The user can select from the list or type in the edit area.

1	Simple Combo.  Includes an edit area and a list that is always displayed.  The user can select from the list or type in the edit area.  The size of a Simple Combo box includes both the edit and list portions.  By default, a Simple Combo box is sized so that none of the list shows.  Increase the Height property to show more of the list.

2	Dropdown List.  This style only allows selection from the drop-down list.

Remarks

Follow these guidelines in deciding which setting to choose:

Use setting 0 (Dropdown Combo) or setting 1 (Simple Combo) to give the user a list of choices.  Either style enables the user to enter a choice in the edit area.  Style 0 saves space on the form because the list portion closes when the user makes a selection.

Use setting 2 (Dropdown List) to display a fixed list of choices from which the user can select one.  The list portion closes when the user selects an item.

Data Type

Integer (Enumerated)


See Also

Help:

Change Event

Click Event

DblClick Event

DropDown Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TabIndex Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, label, list box, option button, picture box, text box, vertical scroll bar.

Description

Determines the tab order of a control within its parent form.

Usage

[form.]control.TabIndex[ = index ]

Setting

The valid range is any integer from 0 to (n-1), where n is the number of controls on the form that have a TabIndex property.  Assigning a TabIndex value of less than 0 generates an error.

Remarks

By default, Visual Basic assigns a tab order to controls as you draw them on a form.  Each new control is placed last in the tab order.  If you change the value of a control's TabIndex property to adjust the default tab order, Visual Basic automatically renumbers the TabIndex of other controls to reflect insertions and deletions.  You can make changes at design time using the Properties window or at run time in code.

All controls except menus and timers are included in the tab order.  At run time, invisible or disabled controls and controls that cannot receive the focus (frames and labels) remain in the tab order but are skipped during tabbing.

The TabIndex property is not affected by the ZOrder method.

Note	A control's tab order does not affect its associated access key.  If you press the access key for a frame or label, the focus moves to the next control in the Tab order that can receive the focus.

When loading forms saved as ASCII text, controls with a TabIndex property that aren't listed in the form description are automatically assigned a TabIndex value.  In subsequently loaded controls, if existing TabIndex values conflict with earlier assigned values, the controls are automatically assigned new values.

Data Type

Integer


See Also

Help:

Specifying Access Keys

TabStop Property

ZOrder Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TabIndex Property Example

The example reverses the tab order of a group of buttons by changing the TabIndex property on a command button array.  To try this example, paste the code into the Declarations section of a form that contains four command buttons.  Set the Name property to CommandX for each button to create the control array). Then press F5 and click the form to reverse the tab order of the buttons.

Sub Form_Click ()

Dim I, X	' Declare variables.

' Reverse tab order by setting start value of X.

If CommandX(0).TabIndex = 0 Then X = 4 Else X = 1

For I = 0 To 3

CommandX(I).Caption = X	' Set caption.

CommandX(I).TabIndex = X - 1	' Set tab order.

If CommandX(0).TabIndex = 3 Then

X = X - 1	' Decrement X.

Else

X = X + 1	' Increment X.

End If

Next I

End Sub


TabStop Property

See Also

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, option button, picture box, text box, vertical scroll bar.

Description

Determines whether a user can use the Tab key to set the focus to a control.

Usage

[form.]control.TabStop[ = boolean ]

Setting

The TabStop property settings are:

Setting	Description

True	(Default) Designates the control as a tab stop.

False	Bypasses the control when the user is tabbing, although the control still holds its place in the actual tab order, as determined by the TabIndex property.

Remarks

This property allows you to add or remove a control from the tab order on a form.  For example, instead of moving through each button in an option button group, you can treat the whole group as one tab location.  To do this, set TabStop to True for the first option button in the group and set TabStop to False for the other option buttons in the group.

Data Type

Integer (Boolean)


See Also

Help:

Specifying Access Keys

TabIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Tag Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE client, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Stores any extra data needed for your program.  Unlike other properties, the value of the Tag property is not used by Visual Basic; you can use this property to identify objects.

Usage

[form.][control.]Tag[ = expression ]

Remarks

By default, the Tag property is set to an empty string ("").

You can use this property to assign an identification string to an object without affecting any of its other property settings or causing side effects.  The Tag property is useful when you need to check the identity of a control or MDI form that is passed as a variable to a procedure.

Tip	At the time you create a new instance of a form, assign a unique value to the Tag property.

Data Type

String


See Also

Help:

Name Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Tag Property Example

The example displays a unique icon for each control being dragged.  To try this example, paste the code into the Declarations section of a form that contains three picture boxes.  Set the DragMode property for Picture1 and Picture2 to 1.  Then press F5. Use the mouse to drag Picure1 or Picture2 over Picture3 controls.

Sub Form_Load ()

Picture1.Tag = "Pic1"

Picture2.Tag = "Pic2"

End Sub

Sub Picture3_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Const ENTER = 0, LEAVE = 1, OVER = 2

If State = ENTER Then

' Select based on Tag. Name is not available at run time.

Select Case Source.Tag

Case "Pic1"

' Load icon for Picture1.

Source.DragIcon = LoadPicture ("icons\arrows\point03.ico")

Case "Pic2"

' Load icon for Picture 2.

Source.DragIcon = LoadPicture ("icons\arrows\point04.ico")

End Select

ElseIf State = LEAVE Then

' When source is not over Picture3.

Source.DragIcon = LoadPicture ()	'Unload icon.

End If

End Sub


Text Property

See Also	Example

Applies To

Combo box, list box, text box.

Description

Combo box (Style property set to 0 (Dropdown Combo) or to 1 (Simple Combo)) and text box [image] determines the text contained in the edit area.

Combo box (Style property set to 2 (Dropdown List)) and list box [image] determines the selected item in the list box; the value returned is always equivalent to the value returned by the expression List(listindex).  Read-only at design time; read-only at run time.

Usage

[form.]{combobox|listbox|textbox}.Text[ = stringexpression ]

Remarks

At design time only, the defaults for the Text property are:

Combo box and text box [image] the control's Name property.

List box [image] an empty string ("").

For a combo box with Style property set to 0 (Dropdown Combo) or to 1 (Simple Combo), or for a text box, this property is useful for reading the actual string contained in the edit area of the control.  For a setting 2 (Dropdown List) combo box or for a list box, you can use the Text property to determine the currently selected item.

The Text setting for a text box is limited to 2048 characters unless the MultiLine property is True, in which case the limit is about 32k.

Data Type

String


See Also

Help:

SelLength, SelStart, SelText Properties

Value Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Text Property Example

The example illustrates the Text property.  To try this example, paste the code into the Declarations section of a form that contains three text boxes and a command button.  Then press F5 and type something into Text1.

Sub Text1_Change ()

Text2.Text = LCase(Text1.Text)' Display text as lowercase.

Text3.Text = UCase(Text1.Text)	' Display text as uppercase.

End Sub

Sub Command1_Click ()	' Delete text.

Text1.Text = ""

End Sub


Visible Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE client, option button, picture box, shape, text box, vertical scroll bar.

Description

Determines whether an object is visible or hidden.

Usage

[form.][control.]Visible[ = boolean ]

Setting

The Visible property settings are:

Setting	Description

True	(Default) Object is visible.

False	Object is hidden.

Remarks

To hide a control at startup, set the Visible property to False at design time.  Setting this property in code allows you to hide and later redisplay a control at run time in response to a particular event.

Note	Using the Show or Hide method on a form is the same as setting the form's Visible property in code to True or False, respectively.

An MDI child form cannot be hidden.

Data Type

Integer (Boolean)


See Also

Help:

Hide Method

Load Statement

Show Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Visible Property Example

The example creates animation using two picture boxes.  To try this example, paste the code into the Declarations section of a form that contains two icon-sized picture boxes.  Set Name to FileCab for both picture boxes to create an array.  Then press F5 and click the picture control to view the animation.

Sub Form_Load ()

Dim I	' Declare variable.

FileCab(0).BorderStyle = 0	' Set BorderStyle.

FileCab(1).BorderStyle = 0

' Load icons into picture boxes.

FileCab(1).Picture = LoadPicture("icons\office\files03b.ico")

FileCab(0).Picture = LoadPicture("icons\office\files03a.ico")

For I = 0 To 1

FileCab(I).Move 400, 400	' Place pictures at same spot.

Next I

FileCab(1).Visible = False	' Set to invisible.

FileCab(0).Visible = True	' Set to visible.

End Sub

Sub FileCab_Click (Index As Integer)

Dim I	' Declare variable.

For I = 0 To 1

' Switch the visibility for both pictures.

FileCab(I).Visible = Not FileCab(I).Visible

Next I

End Sub


WindowState Property

See Also	Example

Applies To

Form, MDI form.

Description

Determines the visual state of a form window at run time.

Usage

[form.]WindowState[ = state ]

Setting

The WindowState property settings are:

Setting	Description

0	(Default) Normal

1	Minimized (shrunk to an icon)

2	Maximized (enlarged to maximum size)

Remarks

Before a form appears, WindowState is always set to Normal (0), regardless of its initial setting.  This is reflected in the Height, Left, ScaleHeight, ScaleWidth, Top, and Width settings.  If a form is hidden after it's been shown, these properties reflect the previous state until the form is shown again, regardless of any changes made to WindowState in the meantime.

Data Type

Integer (Enumerated)


See Also

Help:

Load Event

Paint Event

Resize Event

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


WindowState Example

The example hides a dialog box (Form2) when the parent form (Form1) is minimized and redisplays the dialog box when the parent form is returned to either a normal or maximized state.  To try this example, paste the code into the Declarations section of Form1 of an application that contains two forms.  Press F5 to start the example.  Move Form1 around so you can see both forms.  Then minimize or maximize the form and observe the action of Form2.

Sub Form_Load ()

Form2.Show	' Show Form2.

End Sub

Sub Form_Resize ()

Const MIN = 1

If Form1.WindowState = MIN Then	' If parent form is minimized,

Form2.Visible = False	' Hide Form2.

Else	' If form is not minimized,

Form2.Visible = True	' Restore Form2.

End If

End Sub


ScrollBars Property

See Also

Applies To

MDI form, grid, text box.

Description

Specifies whether an object has horizontal or vertical scroll bars; read-only at run time.

Usage

{mdiform|grid|textbox}.ScrollBars

Setting

For an MDI form, the ScrollBars property settings are:

Setting	Description

True	(Default) The form has a horizontal or vertical scroll bar, or both.

False	The form has no scroll bars.

For a grid and text box, the ScrollBars property settings are:

Setting	Description

0	(Default) None

1	Horizontal

2	Vertical

3	Both

Remarks

For a text box with settings 1 (Horizontal), 2 (Vertical), or 3 (Both), you must set the MultiLine property to True.

At run time, the Windows environment automatically implements a standard keyboard interface to allow navigation in text box controls with the arrow keys, the Home and End keys, and so on.

Scroll bars appear on an object only if its contents extend beyond the object's borders.  For example, in an MDI form, if part of a child form is hidden behind the border of the parent MDI form, a horizontal scroll bar appears.  Similarly, a vertical scroll bar appears on a grid control when it can't display all of its rows; a vertical scroll bar appears on a text box when it can't display all of its lines of text.  If ScrollBars is set to False, the object will not have scroll bars, regardless of its contents.

If no horizontal scroll bar is specified for a text box and MultiLine is True, the text will automatically wrap even if the WordWrap property is False.

Data Type

Integer (Enumerated or Boolean)


See Also

Help:

MultiLine Property

WordWrap Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Parent Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE client, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Specifies the form on which a control is located; not available at design time and read-only at run time.

Usage

[form.]control.Parent

Remarks

Use the Parent property to access the properties, methods, or controls of a control's parent form [image] for example, MyButton.Parent.MousePointer = 4.

The Parent property is useful in an application in which you pass controls as arguments.  For example, you might pass a control variable to a general procedure in a module, and use the Parent property to access its parent form.

Note	There is no relationship between the Parent property and the MDIChild property.  There is, however, a parent-child relationship between an MDI form and any forms in your project that have the MDIChild property set to True.

Data Type

Form


See Also

Help:

ActiveControl Property

ActiveForm Property

Programmer's Guide:

Chapter 8, "Objects and Instances"


Parent Property Example

The example passes a control from a form that doesn't have the focus to a procedure in a module, and then prints the state of the control on the parent form.  To try this example, create three forms: Form1, containing a command button; and Form2 and Form3, each containing a check box. You must also create a new module (choose the New Module command from the File menu).  Paste the code into the Declarations sections of the respective forms or module and then press F5 to run the program.

' Enter into Form1:

Sub Form_Load ()

Form2.Show	' Display all forms.

Form3.Show

Form2.AutoRedraw = True

Form3.AutoRedraw = True

End Sub

Sub Command1_Click ()

CheckCheck Form2.Check1	' Call procedure in other module.

CheckCheck Form3.Check1	' And send control as argument.

End Sub

' Enter into Module1:

Sub CheckCheck (Source As Control)

If Source.Value Then

Source.Parent.Cls	' Clear parent form.

Source.Parent.Print "CheckBox is ON"	' Print on parent form.

Else

Source.Parent.Cls	' Clear parent form.

Source.Parent.Print "CheckBox is OFF"	' Print on parent form.

End If

End Sub


Alignment Property

See Also

Applies To

Check box, label, option button, text box.

Description

Determines the alignment of a check box, option button, or text in a control.  Read-only at run time for check box, option button, and text box.

Usage

[form.]control.Alignment[ = numericexpression ]

Setting

For a check box and option button, the Alignment property settings are:

Setting	Description

0	(Default) Control aligns to the left with text on the right.

1	Control aligns to the right with text on the left.

For a label and text box, the Alignment property settings are:

Setting	Description

0	(Default) Text aligns to the left.

1	Text aligns to the right.

2	Text aligns to the center (in Microsoft Windows version 3.0, aligns to the left).

Remarks

You can have text appear to the right or left of option buttons and check boxes, as in the following illustration.  Notice that text always aligns to the left.

If the MuliLine property of a text box is False, the Alignment property is ignored.

Data Type

Integer (Enumerated)


See Also

Help:

Align Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


BackColor, ForeColor Properties

See Also	Example

Apply To

Form, check box, combo box, command button (BackColor only), directory list box, drive list box, file list box, frame, grid, label, list box, OLE client, option button, picture box, Printer object (ForeColor only), shape (BackColor only), text box.

Description

BackColor [image] determines the background color of an object.

ForeColor [image] determines the foreground color used to display text and graphics in an object.

Usage

[form.][control.]BackColor[ = color ]

[form.][control.]ForeColor[ = color ]

Remarks

Visual Basic uses the Microsoft Windows environment RGB scheme for colors.  Each property has the following ranges of settings:

Range of settings	Description

Normal RGB colors	Colors specified by using the Color palette, or by using the RGB or QBColor functions in code.

System default colors	Colors specified with system color constants from CONSTANT.TXT, a Visual Basic file that specifies system defaults.  The Windows environment substitutes the user's choices as specified in the user's Control Panel settings.

For all forms and controls, the default settings at design time are:

BackColor [image] set to the WINDOW_BACKGROUND system default color as specified in CONSTANT.TXT.

ForeColor [image] set to the WINDOW_TEXT system color as specified in CONSTANT.TXT.

In labels and shapes, the BackColor property is ignored if the BackStyle property is 0 (Transparent).

If you set the BackColor property on forms or picture boxes, all graphics and print output, including the persistent bitmap, are erased.  Setting the ForeColor property does not affect graphics or print output already drawn.  On all other controls, the screen color changes immediately.

The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF).  The high byte of a number in this range equals 0; the lower three bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively.  The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).  If the high byte is not 0, Visual Basic uses the system colors, as defined in the user's Control Panel and enumerated in CONSTANT.TXT.

To display text in the Windows environment, both the text and background colors must be solid.  If the text or background colors you've selected are not displayed, one of the selected colors may be dithered [image] that is, comprised of up to three different-colored pixels.  If you choose a dithered color for either the text or background, the nearest solid color will be substituted.


See Also

Help

Creating Custom Colors

FillColor Property

FillStyle Property

Setting Colors

Programmer's Guide

Chapter 15, "Creating Graphics for Applications"


BackColor, ForeColor Properties Example

The example resets background colors randomly twice each second for a form and picture box.  To try this example, paste the code into the Declarations section of a form that contains a picture box control and a timer control.  Then press F5.

Sub Form_Load ()

Timer1.Interval = 500

End Sub

Sub Timer1_Timer ()

BackColor = QBColor(Rnd * 15)

Picture1.BackColor = QBColor(Rnd * 15)

End Sub


BorderColor Property

See Also

Applies To

Line, shape.

Description

Determines the color of a control's border.

Usage

[form.]{line|shape}.BorderColor[ = color ]

Setting

Visual Basic uses the Microsoft Windows environment RGB scheme for colors.  The BorderColor property has the following range of settings:

Range of settings	Description

Normal RGB colors	Colors specified by using the Color palette, or by using the RGB or QBColor functions in code.

System default colors	Colors specified with system color constants from CONSTANT.TXT, a Visual Basic file that specifies system defaults.  The Windows environment substitutes the user's choices, as specified in the user's Control Panel settings.

The default setting for BorderColor is the WINDOW_TEXT system default color, as specified in CONSTANT.TXT.

Remarks

The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF).  The high byte of a number in this range equals 0; the lower three bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively.  The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).  If the high byte is not 0, Visual Basic uses the system colors, as defined in the user's Control Panel and enumerated in CONSTANT.TXT.

Data Type

Long


See Also

Help:

BackColor, ForeColor Properties

DrawWidth Property

Programmer's Guide

Chapter 15, "Creating Graphics for Applications"


BorderWidth Property

See Also	Example

Applies To

Line, shape.

Description

Determines the width of a control's border.

Usage

[form.]{line|shape}.BorderWidth[ = numericexpression ]

Remarks

The BorderWidth property settings can range from 1 to 8192, inclusive.

Use the BorderWidth and BorderStyle properties to specify the kind of border you want for a line and shape control.  The following table shows the effect of BorderStyle settings on the BorderWidth property:

BorderStyle	Effect on BorderWidth

0	BorderWidth setting is ignored.

1 to 5	The border width expands from the center of the border; the height and width of the control are measured from the center of the border.

6	The border width expands inward on the control from the outside of the border; the height and width of the control are measured from the outside of the border.

If BorderWidth is greater than 1, the only effective settings of BorderStyle are 1 (Solid), and 6 (Inside Solid).

Data Type

Integer


See Also

Help:

BorderStyle Property

DrawWidth Property

Height, Width Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


BorderWidth Property Example

The example uses two combo boxes to select different widths and styles for the borders of a shape control.  To try this example, paste the code into the Declarations section of a form that contains a shape control and one combo box.  For the combo box, set Style = 2 and Index = 0 (to create a control array).  Then press F5 and click the form.

Sub Form_Load ()

Combo1(0).Width = 1440 * 1.5

Load Combo1(1)

Combo1(1).Top = Combo1(0).Top + Combo1(0).Height * 1.5

Combo1(1).Visible = True

For I = 0 To 6

Combo1(0).AddItem "BorderStyle = " & I

Next I

For I = 1 To 10

Combo1(1).AddItem "BorderWidth = " & I

Next I

Combo1(0).ListIndex = 1

Combo1(1).ListIndex = 0

End Sub

Sub Combo1_Click (Index As Integer)

If Index = 0 Then

Shape1.BorderStyle = Combo1(0).ListIndex

Else

Shape1.BorderWidth = Combo1(1).ListIndex + 1

End If

End Sub


ClipControls Property

See Also	Example

Applies To

Form, frame, picture box.

Description

Determines whether graphics methods in Paint events repaint the entire object or only newly exposed areas.  Also determines whether the Windows environment creates a clipping region that excludes non-graphic controls contained by the object.

Usage

[form.][frame.|picturebox.]ClipControls

Setting

The ClipControls property settings are:

Setting	Description

True	(Default) Graphics methods in Paint events repaint the entire object.  A clipping region is created around non-graphical controls on the form before a Paint event.

False	Graphics methods in Paint events repaint only newly exposed areas.  A clipping region is not created around non-graphical controls before a Paint event.  Complex forms usually load and repaint faster.

Remarks

Clipping is the process of determining which parts of a form or container, such as a frame or picture box, are painted when the form is displayed.  An outline of the form and controls is created in memory.  The Windows environment uses this outline to paint some parts, such as the background, without affecting other parts, such as the contents of a text box.  Since the clipping region is created in memory, setting this property to False can reduce the time needed to paint or repaint a form.

The clipping region includes most controls, but does not clip around the image, label, line, or shape controls.

Data Type

Integer (Boolean)


See Also

Help:

AutoRedraw Property

Circle Method

Line Method

Paint Event

Print Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ClipControls Property Example

The example shows how the ClipControls property affects the repainting of a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Notice that the color of the entire form changes each time you resize it or cover part of it with another form or application.  End the program and change ClipControls to False and then run the program again.  Notice that only newly exposed parts of the form are repainted.

Sub Form_Paint ()

' Select a random color for the background.

BackColor = &HFFFFFF * Rnd

End Sub


Count Property

See Also

Applies To

Forms collection, Controls collection.

Description

Forms collection [image] specifies the number of loaded forms.

Controls collection [image] specifies the number of controls on a form, including menus and menu items.

Not available at design time; read-only at run time.

Usage

[form.]Controls.Count

Forms.Count

Remarks

You can use this property in a For...Next loop to specify the number of forms or controls in a collection.  For example, the following code would move all controls on a form one-half inch to the right (ScaleMode = 0):

For I = 0 to Form1.Count - 1

Form1.Controls(I).Left = Form1.Controls(I).Left + 720

Next I

You can also use this kind of structure to quickly enable or disable all controls on a form.

When used with the If Type Of statement, you can cycle through all controls and change, for example, the values of only the text boxes, or the BackColor setting of all the option buttons.

Data Type

Integer


See Also

Programmer's Guide:

Chapter 8, "Objects and Instances"


CurrentX, CurrentY Properties

See Also

Apply To

Form, picture box, Printer object.

Description

Determine the horizontal (CurrentX) and vertical (CurrentY) coordinates for the next printing or drawing method.  Not available at design time.

Usage

{[form.][picturebox.]|Printer.}CurrentX[ = x ]

{[form.][picturebox.]|Printer.}CurrentY[ = y ]

Remarks

Coordinates are measured from the upper-left corner of an object.  CurrentX is 0 at an object's left edge and CurrentY is 0 at its top edge.  Coordinates are expressed in twips, or the current scale defined by the ScaleHeight, ScaleWidth, ScaleLeft, ScaleTop, and ScaleMode. properties.

When you use the following graphics methods, the CurrentX and CurrentY settings are changed as indicated:

This method	Sets CurrentX, CurrentY to

Circle	The center of the object.

Cls	0, 0

EndDoc	0, 0

Line	The end point of the line.

NewPage	0, 0

Print	The next print position.

PSet	The point drawn.

Data Type

Single


See Also

Help:

Circle Method

Cls Method

DrawMode Property

DrawStyle Property

Left, Top Properties

Line Method

PSet Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


EXEName Property

See Also

Applies To

App object.

Description

Specifies the root name of the executable file (without the extension) that is currently running.  If running in the development environment, specifies the name of the project.  Read-only at run time.

Usage

App.EXEName

Remarks

Use this property to identify your application in calls to the Windows API.

If you have a Save As command on a menu in your application, you can use the EXEName property to make sure a user doesn't accidentally try to save a file with the same name as your application.


See Also

Help:

Using Dynamic Data Exchange (DDE)

Make EXE File Command (File Menu)

Programmer's Guide:

Chapter 17, "Interacting with the Environment"

Chapter 21, "Object Linking and Embedding (OLE)"


FillStyle Property

See Also	Example

Applies To

Form, grid, picture box, Printer object, shape.

Description

Determines the pattern used to fill shape controls as well as circles and boxes created with the Circle and Line graphics methods.

Usage

{[form.][control.]|Printer.}FillStyle[ = style ]

Setting

The FillStyle property settings are:

Setting	Description

0	Solid

1	(Default) Transparent

2	Horizontal Line

3	Vertical Line

4	Upward Diagonal

5	Downward Diagonal

6	Cross

7	Diagonal Cross

Remarks

When FillStyle is 1 (Transparent), the FillColor property is ignored.

Data Type

Integer (Enumerated)


See Also

Help:

BorderStyle Property

Paint Event

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


FillStyle Property Example

The example displays a circle on a form with random FillColors and FillStyles as you click the mouse button.  To try this example, paste the code into the Declarations section and then press F5 to run the program.

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

FillColor = QBColor(Rnd * 15)	' Choose random FillColor.

FillStyle = Rnd * 8	' Choose random FillStyle.

Circle (X, Y), 250	' Draw a circle.

End Sub


hWnd Property

See Also	Example1	Example2

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, list box, OLE client, option button, picture box, scroll bar.

Description

Specifies a handle to a form or control.  Not available at design time; read-only at run time.

Usage

[form.][control.]hWnd

Remarks

The Windows environment identifies each form and control in an application by assigning it a handle, or hWnd.  The hWnd is used with Windows API calls.  Many Windows environment functions require the hWnd of the current window as an argument.

Note	Because the value of this property can change while a program is running, never store the hWnd value in a variable.

Data Type

Integer


See Also

Help:

Declare Statement

hDC Property

Icon Property

Programmer's Guide:

Chapter 22, "Calling Procedures in DLLs"


hWnd Property Example 1

The example forces a form to always remain on top.  To try this example, create a form (not an MDI child form) and set its Caption property to "Always on top."  Then give the form a menu containing a menu item named "mnuTopmost."  Make sure the Declare statement is all on one line.  Paste the code into the Declarations section of the form and press F5.  (This example requires Microsoft Windows version 3.1.)

' Declare the Windows 3.1 API routine.

Declare Sub SetWindowPos Lib "User" (ByVal h1, ByVal h2, ByVal x, ByVal y, ByVal cx, ByVal cy, ByVal f)

' Set some constant values (from WINAPI.TXT).

Const HWND_TOPMOST = -1

Const HWND_NOTOPMOST = -2

Const SWP_NOACTIVATE = &H10

Const SWP_SHOWWINDOW = &H40

Sub mnuTopmost_Click ()

' Add or remove the checkmark from the menu.

mnuTopmost.Checked = Not mnuTopmost.Checked

If mnuTopmost.Checked Then

' Turn on the TopMost attribute.

SetWindowPos hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE Or SWP_SHOWWINDOW

Else

' Turn off the TopMost attribute.

SetWindowPos hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE Or SWP_SHOWWINDOW

End If

End Sub


hWnd Property Example 2

The example automatically drops down the list portion of a combo box whenever the combo box gets the focus.  To try this example, create a new form containing a combo box and option button (the option button is used only to receive the focus).  Make sure the Declare statement is all on one line.  Paste the code into the Declarations section of the form and press F5.  Use the Tab key to move the focus to and from the combo box.

Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal Msg As Integer, ByVal Wp As Integer, Lp As Any) As Long

Const WM_USER = &H400

Sub Combo1_GotFocus ()

Const CB_SHOWDROPDOWN = WM_USER + 15

Dim Tmp

Tmp = SendMessage(Combo1.hWnd, CB_SHOWDROPDOWN, 1, ByVal 0&)

End Sub


PrevInstance Property

See Also

Applies To

App object.

Description

Specifies whether a previous instance of an application is already running.  Not available at design time; read-only at run time.

Usage

App.PrevInstance

Remarks

You can use this property in a Form_Load procedure to specify whether a user is already running an instance of an application.  Depending on the application, you might want only one instance running in the Windows environment at a time.

Data Type

Integer (Boolean)


See Also

Programmer's Guide:

Chapter 8, "Objects and Instances"


ScaleHeight, ScaleWidth Properties

See Also	Example

Apply To

Form, MDI form, picture box, Printer object.

Description

Determine the number of units for the internal horizontal (ScaleWidth) and vertical (ScaleHeight) measurement of an object when using graphics methods or when positioning controls.  For MDI forms, not available at design time and read-only at run time.

Usage

{[form.][picturebox.]|Printer.}ScaleHeight[ = numericexpression ]

{[form.][picturebox.]|Printer.}ScaleWidth[ = numericexpression ]

Remarks

You can use these properties to create a custom coordinate scale for drawing or printing.  For example, the statement ScaleHeight = 100 defines the internal height of a section as 100 units, or one vertical unit as 1/100 of the height.

Use the ScaleMode property to define a scale based on a standard unit of measurement, such as twips, points, pixels, characters, inches, millimeters, or centimeters.

Setting these properties to positive values makes coordinates increase from top to bottom and left to right.  Setting them to negative values makes coordinates increase from bottom to top and right to left.

Using these properties and the related ScaleLeft and ScaleTop properties, you can set up a full coordinate system with both positive and negative coordinates.  All four of these scale properties interact with the ScaleMode property in the following ways:

Setting any other scale property to any value automatically sets ScaleMode to 0.

Setting ScaleMode to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0.  In addition, the CurrentX and CurrentY settings will change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note	TheScaleHeight and ScaleWidth properties aren't the same as the Height and Width properties.

For MDI forms, ScaleHeight and ScaleWidth refer only to the area not covered by picture boxes in the form.  Avoid using these properties to size a picture box in the Resize event of an MDI form.

Data Type

Single


See Also

Help:

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Scale Method

ScaleLeft, ScaleTop Properties

ScaleMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ScaleHeight, ScaleWidth Properties Example

The example uses the ScaleHeight and ScaleWidth properties to change the vertical and horizontal units of measurement for a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  To see the effect, click the form, resize it, then click it again.

Sub Form_Click ()

Dim Radius As Integer	' Declare variable.

ScaleHeight = 100	' Set height units.

ScaleWidth = 100	' Set width units.

For Radius = 5 to 50 Step 5

FillStyle = 1

Circle (50, 50), Radius	' Draw  circle.

Next Radius

End Sub


ScaleLeft, ScaleTop Properties

See Also	Example

Apply To

Form, picture box, Printer object.

Description

Determine the horizontal (ScaleLeft) and vertical (ScaleTop) coordinates for the left and top edges of an object when using graphics methods or when positioning controls.  The default for both properties is 0.

Usage

{[form.][picturebox.]|Printer.}ScaleLeft[ = numericexpression ]

{[form.][picturebox.]|Printer.}ScaleTop[ = numericexpression ]

Remarks

Using these properties and the related ScaleHeight and ScaleWidth properties, you can set up a full coordinate system with both positive and negative coordinates.  These four scale properties interact with the ScaleMode property in the following ways:

Setting any other scale property to any value automatically sets ScaleMode to 0.

Setting ScaleMode to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0.  The CurrentX and CurrentY property settings will change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note	The ScaleLeft and ScaleTop properties aren't the same as the Left and Top properties.

Data Type

Single


See Also

Help:

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Left, Top Properties

Scale Method

ScaleHeight, ScaleWidth Properties

ScaleMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ScaleLeft, ScaleTop Properties Example

The example creates a grid in a picture box and sets coordinates for the upper-left corner to -1, -1 instead of 0, 0.  Every quarter second, dots are randomly plotted from the upper-left corner to the lower-right corner.  To try this example, paste the code into the Declarations section of a form that contains a large picture box and a timer control.  Then press F5 and click the form.

Sub Form_Load ()

Timer1.Interval = 250	' Set timer interval.

Picture1.ScaleTop = -1	' Set scale for top of grid.

Picture1.ScaleLeft = -1	' Set scale for left of grid.

Picture1.ScaleWidth = 2	' Set scale (-1 to 1).

Picture1.ScaleHeight = 2

Picture1.Line (-1, 0)-(1, 0)	' Draw horizontal line.

Picture1.Line (0, -1)-(0, 1)	' Draw vertical line.

End Sub

Sub Timer1_Timer ()

Dim I	' Declare variable.

' Plot dots randomly within a range.

For I = -1 To 1 Step .05

Picture1.PSet (I * Rnd, I * Rnd)	' Draw a point.

Next I

End Sub


ScaleMode Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Determines the unit of measurement for coordinates of an object when using graphics methods or when positioning controls.

Usage

{[form.][picturebox.]|Printer.}ScaleMode[ = mode ]

Setting

The ScaleMode property settings are:

Setting	Description

0	Indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties are set to custom values.

1	(Default) Twip (1440 twips per logical inch; 567 twips per logical centimeter).

2	Point (72 points per logical inch).

3	Pixel (smallest unit of monitor or printer resolution).

4	Character (horizontal = 120 twips per unit; vertical = 240 twips per unit).

5	Inch.

6	Millimeter.

7	Centimeter.

Remarks

Using the related ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties, you can create a custom coordinate system with both positive and negative coordinates.  These four scale properties interact with the ScaleMode property in the following ways:

Setting the value of any other scale property to any value automatically sets ScaleMode to 0.

Setting ScaleMode to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0.  The CurrentX and CurrentY property settings will change to reflect the new coordinates of the current point.

Data Type

Integer (Enumerated)


See Also

Help:

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Scale Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Chapter 16, "Displaying and Printing Information"


ScaleMode Property Example

The example shows how different ScaleMode property settings change the size of a circle.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.   When you click the form, the unit of measurement changes to the next ScaleMode setting and a circle is drawn on the form.

Sub Form_Click ()

' Cycle through each of 7 ScaleModes.

ScaleMode = ((ScaleMode + 1) Mod 7) + 1

' Draw a circle with radius of 2 in center of form.

Circle (ScaleWidth / 2, ScaleHeight / 2), 2

End Sub


Stretch Property

See Also	Example

Applies To

Image

Description

Determines whether a picture stretches to fit the size of an image control.

Usage

[form.]image.Stretch[ = {True|False}]

Setting

The Stretch property settings are:

Setting	Description

True	The picture resizes to fit the control.

False	(Default) The control resizes to fit the picture.

Remarks

If Stretch is True, resizing the control also resizes the picture it contains.

Data Type

Integer (Boolean)


See Also

Help:

Image Property

Picture Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Stretch Property Example

The example loads an arrow icon from your icons directory into an image control.  The arrow crawls across the form when Stretch is True, and hops across the form when Stretch is False.  To try this example, paste the code into the Declarations section of a form that contains an image control, a check box and a timer control.  Then press F5 and click the form.  Be sure to check the path to your icons directory and change it if necessary.  To see the effects of the Stretch property, click the check box and then click the form again.

Dim ImgW	' Declare variable.

Sub Form_Load ()

' Load an icon into the image control.

Image1.Picture = LoadPicture("icons\arrows\arw02rt.ico")

Image1.Left = 0	' Move image to left edge.

ImgW = Image1.Width	' Save width of image.

Timer1.Interval = 300

Timer1.Enabled = False	' Turn off timer.

Check1.Caption = "Stretch Property"

End Sub

Sub Form_Click ()

Timer1.Enabled = True	' Turn on the timer.

End Sub

Sub Timer1_Timer ()

Static MoveIcon As Integer	' Flag for moving the icon.

If Not MoveIcon Then

Image1.Move Image1.Left + ImgW, Image1.Top, ImgW * 2

Else

' Move the image and return it to original width.

Image1.Move Image1.Left + ImgW, Image1.Top, ImgW

End If

' If image is off edge of form, start over.

If Image1.Left > ScaleWidth Then

Image1.Left = 0

Timer1.Enabled = False

End If

MoveIcon = Not MoveIcon	' Reset flag.

End Sub

Sub Check1_Click ()

Image1.Stretch = Check1.Value

End Sub


TwipsPerPixelX, TwipsPerPixelY Properties

See Also

Apply To

Screen object, Printer object.

Description

Specify the number of twips per pixel for the object measured horizontally (TwipsPerPixelX) or vertically (TwipsPerPixelY).  Not available at design time; read-only at run time.

Usage

{Screen|Printer}.TwipsPerPixelX

{Screen|Printer}.TwipsPerPixelY

Remarks

Windows API routines generally require measurements in pixels.  You can use these properties to convert measurements quickly without changing an object's ScaleMode setting.

Data Type

Integer


See Also

Help:

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


AutoRedraw Property

See Also	Example

Applies To

Form, picture box.

Description

Determines the output from a graphics method to a persistent bitmap.

Usage

[form.][picturebox.]AutoRedraw[ = {True|False}]

Setting

The AutoRedraw property settings are:

Setting	Description

True	Enables automatic repainting of a form or picture box. Graphics and print output are written to the screen and to an image stored in memory. The object does not receive Paint events; it is repainted when necessary, using the memory image.

False	(Default) Disables automatic repainting of an object and writes graphics or print output only to the screen. Visual Basic invokes the object's Paint event when necessary to repaint the object.

Remarks

This property is central to working with the graphics methods [image] Circle, Cls, Line, Point, Print, and PSet.  Setting AutoRedraw to True automatically redraws the output from these methods in a form or picture box when, for example, the object is resized or redisplayed after being hidden by another window.

You can reset AutoRedraw in code at run time to alternate between drawing persistent graphics (such as a background or grid) and temporary graphics. If you disable AutoRedraw, previous output becomes part of the background screen. When AutoRedraw is set to False, background graphics are not deleted if you clear the drawing area with the Cls method. Setting AutoRedraw back to True and then using Cls clears the background graphics.

Note	If you set the BackColor property, all graphics and print output, including the persistent bitmap, are erased.  In general, all graphics should be in a Paint event unless AutoRedraw is set to True.

To retrieve the persistent bitmap created when AutoRedraw is set to True, use the Image property.  To pass the persistent bitmap to a Windows API when AutoRedraw is set to True, use the object's hDC property.

When you minimize a form whose AutoRedraw property is set to False, the ScaleHeight and ScaleWidth properties are set to icon size.  When AutoRedraw is set to True, ScaleHeight and ScaleWidth remain the size of the restored window.

Data Type

Integer (Boolean)


See Also

Help:

Circle Method

Cls Method

Image Property

Line Method

Paint Event

Point Method

Print Method

PSet Method

ScaleHeight, ScaleWidth Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


AutoRedraw Property Example

The example alternately displays two drawings on a picture box control: a persistent filled circle and temporary vertical lines.  Click the picture box to draw or redraw the lines.  Resizing the form requires the temporary drawing to be redrawn.  To try this example, paste the code into the Declarations section of a form that has a picture box control named Picture1.  Press F5 to run the program and click the picture each time you resize the form.

Sub Form_Load ()

Picture1.ScaleHeight = 100	' Set scale to 100.

Picture1.ScaleWidth = 100

Picture1.AutoRedraw = True	' Turn on AutoRedraw.

Picture1.ForeColor = 0	' Set ForeColor.

Picture1.FillColor = QBColor(9)	' Set FillColor.

Picture1.FillStyle = 0	' Set FillStyle.

Picture1.Circle (50, 50), 30	' Draw a circle.

Picture1.AutoRedraw = False	' Turn off AutoRedraw.

End Sub

Sub Picture1_Click ()

Dim I	' Declare variable.

Picture1.ForeColor = Rgb(Rnd * 255, 0, 0)	' Select random color.

For I = 5 To 95 Step 10	' Draw lines.

Picture1.Line (I, 0)-(I, 100)

Next

End Sub


AutoSize Property

 See Also

Applies To

Label, picture box.

Description

Determines whether a control is automatically resized to fit its contents.

Usage

[form.]{label|picturebox}.AutoSize[ = {True|False}]

Remarks

The AutoSize property settings are:

Setting	Description

True 	Automatically resizes the control to fit its contents.

False 	(Default) Keeps the size of the control constant. Contents are clipped when they exceed the area of the control.

Data Type

Integer (Boolean)


See Also

Help:

Alignment Property

Resize Event

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Default Property

See Also

Applies To

Command button.

Description

Determines which command button is the default button on a form.

Usage

[form.]commandbutton.Default[ = {True|False}]

Setting

The Default property settings are:

Setting	Description

True 	The command button is the default button.  Only one button on a form can be the default button.  When Default is set to True for one button, it is automatically set to False for all other buttons on the form.  When the button's Default property is True and its parent form is active, the user can choose the button (invoking its Click event) by pressing the Enter key.  Any other control with the focus does not receive a keyboard event (KeyDown, KeyPress, or KeyUp) for the Enter key unless the user has moved the focus to another command button on the same form.  In this case, pressing Enter chooses that button instead of the default button.

False 	(Default) The command button is not the default button.

Remarks

For a form or dialog box that supports an irreversible action such as a delete operation, make the Cancel button the default button by setting its Default property to True.

Data Type

Integer (Boolean)


See Also

Help:

Cancel Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


FontName Property

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, label, list box, option button, picture box, Printer object, text box.

Description

Determines the font used to display text in a control or in a run-time drawing or printing operation.

Usage

{[form.][control.]|Printer.}FontName[ = font ]

Remarks

The default for this property is determined by the system.  Fonts available with Visual Basic vary according to your system configuration, display devices, and printing devices.  Font-related properties can be set only to values for which fonts exist.

In general, you should change FontName before setting size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties.

On systems running Windows 3.0, the fonts "Helv" or "Tms Rmn" are called "MS Sans Serif" and "MS Serif", respectively.  In code, if you set FontName to "Helv," then test whether the FontName is set to "Helv," the result would be False, since it will have been changed internally to "MS Sans Serif."

Note	At run time, you can get information on fonts available to the system through the FontCount and Fonts properties.

Data Type

String


See Also

Help:

FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

FontSize Property

Print Method

TextHeight Method

TextWidth Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontName Property Example

The example prints the name of each font using the particular font.  To try this example, paste the code into the Declarations section of a form.  Press F5 to run the program and then click the form. Each time you click the form, the font name is printed.

Sub Form_Click ()

Static I	' Declare variables.

Dim OldFont

OldFont = FontName	' Preserve original font.

FontName = Screen.Fonts(I)	' Change to new font.

Print Screen.Fonts(I)	' Print name of font.

I = I + 1	' Increment counter.

If I = FontCount Then I = 0	' Start over.

FontName = OldFont	' Restore original font.

End Sub


Fonts Property

See Also	Example

Applies To

Printer object, Screen object.

Description

Specifies all font names available for the current display device or active printer when enumerated from 0 to FontCount - 1.  Not available at design time; read-only at run time.

Usage

{Printer|Screen}.Fonts(index)

Remarks

The Fonts property works in conjunction with the FontCount property, which returns the number of font names available for the object.  Fonts available in Visual Basic vary according to your system configuration, display devices, and printing devices.  Use both the Fonts and the FontCount properties to get information about available screen or printer fonts.

Data Type

String


See Also

Help:

FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

FontName Property

FontSize Property

TextHeight Method

TextWidth Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Fonts Property Example

The example prints a list of the printer fonts in a list box.  To try this example, paste the code into the Declarations section of a form that has a list box control named List1.  Press F5 to run the program and then click the form.

Sub Form_Click ()

Dim I	' Declare variable.

For I = 0 To Printer.FontCount -1	' Determine number of fonts.

List1.AddItem Printer.Fonts (I)	' Put each font into list box.

Next I

End Sub


FontSize Property

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, label, list box, option button, picture box, Printer object, text box.

Description

Determines the size of the font to be used for text displayed in a control or in a run-time drawing or printing operation.

Usage

{[form.][control.]|Printer.}FontSize[ = points ]

Remarks

Use this property to format text in the font size you want.  The default is determined by the system.  To change the default, specify the size of the font in points.

The maximum value for FontSize is 2048 points.

Note	Fonts available with Visual Basic vary according to your system configuration, display devices, and printing devices.  Font-related properties can be set only to values for which fonts exist.

In general, you should change the FontName property setting before you set size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties.  One exception to this is when you need to set font sizes less than 8 pt with TrueType fonts.  In this case, you should set the point size with the FontSize property, then set the FontName property, and finally, set the size again with the FontSize property.  The reason is that Windows actually uses a different font for TrueType fonts that are less than 8 points in size.

Data Type

Single


See Also

Help:

FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

FontCount Property

Fonts Property

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontSize Property Example

The example prints text on your form in two different point sizes with each click of the mouse.  To try this example, paste the code into the Declarations section of a form.  Press F5 to run the program and then click the form.

Sub Form_Click ()

FontSize = 24	' Set FontSize.

Print "This is 24 point type."	' Print large type.

FontSize = 8	' Set FontSize

Print "This is 8 point type."	' Print small type.

End Sub


Image Property

See Also	Example

Applies To

Form, picture box.

Description

Specifies a handle to a persistent bitmap; the handle is provided by the system.  Not available at design time; read-only at run time.

Usage

[form.][picturebox.]Image

Remarks

This property is a Microsoft Windows environment bitmap handle.

An object's AutoRedraw property determines whether the repainting of an object occurs with a persistent bitmap or through Paint events.  The operating environment identifies an object's persistent bitmap by assigning a handle to it; you can use the Image property to get this handle.

An Image value exists regardless of the setting for AutoRedraw.  If AutoRedraw is True and nothing has been drawn, the image contains only the color set with the BackColor property and the picture.

You can assign the value of Image to the Picture property.  The Image property also provides a value to pass to Windows API calls.

The Image, DragIcon, and Picture properties must be used directly when assigning values to other properties, when saving with the SavePicture statement, or when placing something onto the Clipboard.  You cannot assign these to temporary variables and then use the results.

The AutoRedraw property can cause Image, which is a handle to a bitmap, to change.  When AutoRedraw is True, an object's hDC property becomes a handle to a device context that contains the Image bitmap.

Data Type

Integer


See Also

Help:

AutoRedraw Property

BackColor Property

DragIcon Property

Paint Event

Picture Property

Picture Property

SavePicture Statement

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Image Property Example

The example draws a circle in the first picture box each time you click it.  When you click the second picture box, the picture from the first picture box is copied into it.  To try this example, paste the code into the Declarations section of a form that has two large, equal-sized picture box controls.  Press F5 to run the program and then click the picture box controls.

Form_Load ()

Picture1.AutoReDraw = True	' Set AutoRedraw True.

End Sub

Sub Picture1_Click ()

Dim PW, PH	' Declare variables.

Picture1.FillStyle = 0	' Set FillStyle to solid.

Picture1.FillColor = QBColor(Int(Rnd * 15))	' Choose random color.

PW = Picture1.ScaleWidth	' Set ScaleWidth.

PH = Picture1.ScaleHeight	' Set ScaleHeight.

' Draw a circle in random location.

Picture1.Circle (Int(Rnd * PW), Int(Rnd * PH)), 250

End Sub

Sub Picture2_Click ()

Picture2.Picture = Picture1.Image	' Copy Image to Picture2.

End Sub


Index Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE client, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Specifies the number that uniquely identifies a control in a control array; only available if the control is part of a control array; read-only at run time.

Usage

[form.]control [(i)].Index

Setting

The Index property settings are:

Setting	Description

No value	(Default) Not part of an array.

0 to 32,767	Part of an array.  Specify an integer greater than or equal to 0 to assign a control to a control array.  Or, specify the same name for two or more controls through the Name property.  Visual Basic automatically assigns the first unique index available within the control array.

Remarks

Because control array elements share the same Name property setting, you must use the Index property in code to refer to a particular control in the array.  The Index must appear as a number in parentheses next to the control array name [image] for example, MyButtons(3).

When a control in the array recognizes that an event has occurred, Visual Basic calls the array's event procedure and passes the applicable Index as an additional argument.  This property is also used when you create controls dynamically at run time with the Load statement or remove them with the Unload statement.

Note	To remove a control from a control array, change the control's Name property setting.

Data Type

Integer


See Also

Help:

Creating a Control Array

Creating a Menu Bar

Tag Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"


Index Property Example

The example starts with two option buttons and adds new option buttons to the form each time you click a command button.  When you click an option button, the FillStyle property is set and a new circle is drawn.  To try this example, paste the code into the Declarations section of a form that has two option buttons (set the Name property to optButton for both buttons to create an array), a command button, and a large picture box.

Sub OptButton_Click (Index As Integer)

Dim H, W	' Declare variables.

Picture1.Cls	' Clear picture.

Picture1.FillStyle = Index	' Set FillStyle.

W = Picture1.ScaleWidth / 2	' Get size of circle.

H = Picture1.ScaleHeight / 2

Picture1.Circle (W, H), W / 2	' Draw circle.

End Sub

Sub Command1_Click ()

Static MaxIdx	' Largest index in array.

If MaxIdx = 0 Then MaxIdx = 1	' Preset MaxIdx.

MaxIdx = MaxIdx + 1	' Increment index.

If MaxIdx > 7 Then Exit Sub	' Put only 8 buttons on form.

Load OptButton(MaxIdx)	' Create new item in array.

' Set location of new option button under previous button.

OptButton(MaxIdx).Top = OptButton(MaxIdx - 1).Top + 360

OptButton(MaxIdx).Visible = True	' Make new button visible.

End Sub


MousePointer Property

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, frame, horizontal scroll bar, image, label, list box, option button, picture box, Screen object, text box, vertical scroll bar.

Description

Determines the type of mouse pointer displayed when the mouse is over a particular part of a form or control at run time.

Usage

{[form.][control.]|Screen.}MousePointer[ = setting ]

Setting

The MousePointer property settings are:

Setting	Description

0	(Default) Shape determined by the control

1	Arrow

2	Cross (cross-hair pointer)

3	I-Beam

4	Icon (small square within a square)

5	Size (four-pointed arrow pointing north, south, east, west)

6	Size NE SW (double arrow pointing northeast and southwest)

7	Size N S (double arrow pointing north and south)

8	Size NW SE (double arrow pointing northwest and southeast)

9	Size W E (double arrow pointing west and east)

10	Up Arrow

11	Hourglass (wait)

12	No Drop

Remarks

The MousePointer property controls the shape of the mouse pointer.  This property is useful when you want to indicate changes in functionality as the mouse pointer passes over controls on a form or dialog box.  The Hourglass setting (11) is useful for indicating that the user should wait for a process or operation to finish.

Note	When set for the Screen object, MousePointer changes across the entire screen; that is, it overrides all MousePointer settings for other objects and other applications.  Setting MousePointer to 0 (default) restores the previous behavior.

Data Type

Integer


See Also

Help:

DragIcon Property

MouseMove Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


MousePointer Property Example

The example changes the pointer to an hourglass while circles are drawn across your screen, and then changes the hourglass back to a pointer at the end of the procedure.  To try this example, paste the code into the Declarations section of a form.  Press F5 to run the program and then click the form.

Sub Form_Click ()

Dim I	' Declare variable.

Screen.MousePointer = 11	' Change pointer to hourglass.

' Set random color and draw circles on form.

For I = 0 To ScaleWidth Step 50

ForeColor = RGB(Rnd * 255, Rnd * 255, Rnd * 255)

Circle (I, ScaleHeight * Rnd), 400

Next

Screen.MousePointer = 0	' Return pointer to normal.

End Sub


MultiLine Property

See Also

Applies To

Text box.

Description

Specifies whether a text box can accept and display multiple lines of text; read-only at run time.

Usage

[form.]textbox.MultiLine

Setting

The MultiLine property settings are:

Setting	Description

True 	Allows multiple lines of text.

False 	(Default) Ignores carriage returns and restricts data to a single line.

Remarks

A multiline text box wraps text as the user types text extending beyond the display area.

You can also add scroll bars to larger text boxes using the ScrollBars property.  If no horizontal scroll bar is specified, the text in a multiline text box automatically wraps.

Note	On a form with no default button, pressing Enter in a multiline text box moves the focus to the next line.  If a default button exists, you must press Ctrl+Enter to move to the next line.

Data Type

Integer (Boolean)


See Also

Help:

Default Property

ScrollBars Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Picture Property

See Also	Example 1	Example 2

Applies To

Form, image, OLE client, picture box.

Description

Determines a graphic to be displayed in a control.  For OLE client control: not available at design time and read-only at run time.

Usage

[form.][image.|oleclient.|picturebox.]Picture[ = picture ]

Setting

The Picture property settings are:

Setting	Description

(none)	(Default) No picture.

(Bitmap, icon, metafile)	Specifies a graphic.  You can load the graphic from the Properties window at design time.  At run time, you can also set this property using the LoadPicture function on a bitmap, icon, or metafile.

Remarks

At design time, you can transfer a graphic with the Clipboard using the Copy, Cut, and Paste commands on the Edit menu.  At run time, you can use Clipboard methods such as GetData, SetData, and GetFormat with the non-text Clipboard formats CF_BITMAP, CF_METAFILE, and CF_DIB, as defined in CONSTANT.TXT, a Visual Basic file that specifies system defaults.

When setting the Picture property at design time, the graphic is saved and loaded with the form.  If you create an executable file, the file contains the image.  When you load a graphic at run time, the graphic is not saved with the application.  Use the SavePicture statement to save a graphic from a form or picture box into a file.

Note 	At run time, the Picture property can be set to any other object's DragIcon, Icon, Image, or Picture property, or you can assign it the graphic returned by the LoadPicture function.  The Picture property can only be assigned directly.

Data Type

Integer


See Also

Help:

AutoRedraw Property

Icon Property

LoadPicture Function

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Picture Property Example 1

The example loads icons from the Visual Basic Icon Library into two of three picture boxes.  When you click the form, the third picture box is used to switch the bitmaps.  You can use any two icons.  Paste the code into the Declarations section of a form that has three small picture boxes (for Picture3, set Visible = False).  Press F5 to run the program and then click the form.

Sub Form_Load ()

' Load the bitmaps.

Picture1.Picture = LoadPicture("icons\computer\trash02a.ico")

Picture2.Picture = LoadPicture("icons\computer\trash02b.ico")

End Sub

Sub Form_Click ()

Picture3.Picture = Picture1.Picture	' Swap the bitmaps.

Picture1.Picture = Picture2.Picture

Picture2.Picture = Picture3.Picture

' Set the picture to none (not necessary if not visible).

Picture3.Picture = LoadPicture()

End Sub


Picture Property Example 2

The example pastes a bitmap from the Clipboard into a picture box. To find the value of the CF_formats, look at the CONSTANT.TXT file or load it into a module.  To try this example, paste the code into the Declarations section of a form that has a picture box.  Press F5 and then in another application, copy a picture onto the Clipboard, switch to Visual Basic, and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2

Picture1.Picture = Clipboard.GetData(CF_BITMAP)

End Sub


Value Property

See Also	Example

Applies To

Check box, command button, horizontal scroll bar, option button, vertical scroll bar.

Description

Check box, option button [image] determines the state of the control.

Command button [image] determines whether the button is chosen; not available at design time.

Horizontal and vertical scroll bars [image] determines the current position of the scroll bar, whose return value is always between the values for the Max and Min properties, inclusive.

Usage

[form.]control.Value[ = setting ]

Setting

The Value property settings are:

Check box [image] 0 is Unchecked (default), 1 is Checked, and 2 is Grayed (dimmed).

Command button [image] True indicates the button is chosen; False, the default, indicates the button is not chosen.  Setting the Value property to True in code invokes the button's Click event.

Option button [image] True indicates the button is selected; False, the default, indicates the button is not selected.

Horizontal and vertical scroll bars [image] set values between -32,768 and 32,767 to position the scroll box.

Data Type

Check box [image] Integer (Enumerated)

Command button, option button [image] Integer (Boolean)

Horizontal and vertical scroll bars [image] Integer


See Also

Help:

Max Property

Min Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Value Property Example

The example displays a horizontal scroll bar's numeric value in a text box.  To try this example, paste the code into the Declarations section of a form that has a text box and horizontal scroll bar.  Press F5 to run the program and then click the scroll bar.

Sub Form_Load ()

HScroll1.Min = 0	' Initialize scroll bar.

HScroll1.Max = 1000

HScroll1.LargeChange = 100

HScroll1.SmallChange = 1

End Sub

Sub HScroll1_Change ()

Text1.Text = Format (HScroll1.Value)

End Sub


ActiveControl Property

See Also	Example1	Example2

Applies To

Form, MDI form, Screen object.

Description

Specifies the control that has the focus; when a form is referenced, as in ChildForm.ActiveControl, specifies the control that would have the focus if the referenced form were active.  Invalid if all controls on the given form are invisible or disabled.  Not available at design time; read-only at run time.

Usage

{form.|mdiform.|Screen.}ActiveControl

Remarks

You can use ActiveControl to access a control's properties or to invoke its methods [image] for example, Screen.ActiveControl.Tag = "0".

When a control has the focus, it is the active control on the screen (Screen.ActiveControl).  In addition, each form can have a control that is the active control on that form (Form.ActiveControl), regardless of whether or not the form is active.  You can, therefore, write code that manipulates the active control on each form in your application, even when the form is not the active form.

This property is especially useful in an MDI application where a button on a toolbar must initiate an action on a control in an MDI child form.  When a user clicks a Copy button on the toolbar, your code can reference the text in the active control on the MDI child form [image] for example, ActiveForm.ActiveControl.SelText.

Note	If you plan to pass Screen.ActiveControl to a procedure, you must declare the argument in that procedure with the generic type (As Control) rather than a specific form type (As TextBox or As ListBox) [image] even if ActiveControl always refers to the same type of control.

Data Type

Control


See Also

Help:

ActiveForm Property

GotFocus Event

LostFocus Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


ActiveControl Property Example 1

The example displays the text of the active control.  To try this example, paste the code into the Declarations section of a form that contains a text box, a label, and a command button.  Then press F5 and click the form.

Sub Form_Click ()

If TypeOf Screen.ActiveControl Is TextBox Then

Label1.Caption = Screen.ActiveControl.Text

Else

Label1.Caption = "Button: " + Screen.ActiveControl.Caption

End If

End Sub


ActiveForm, ActiveControl Properties Example 2

The example shows how you can use the Clipboard in cut, copy, paste, and delete operations using buttons on a toolbar.  To try this example, draw a text box and a check box on Form1, then create a new MDI form.  On the MDI form, draw a picture box and then draw a command button in the picture box.  Set the Index property on the command button to 0 (this creates a control array).  On Form1, set the MDIChild property to True.

To run the example, copy the code into the Declarations section of the MDI form and press F5.  Notice that if the check box has the focus, the buttons don't work.

Sub MDIForm_Load ()

Dim I	' Declare variable.

Command1(0).Move 0, 0, 700, 300	' Position button on toolbar.

For I = 1 To 3	' Create other buttons.

Load Command1(I)	' Create button.

Command1(I).Move I * 700, 0, 700, 300	' Place and size button.

Command1(I).Visible = True	' Display button.

Next I

Command1(0).Caption = "Cut"	' Set button captions.

Command1(1).Caption = "Copy"

Command1(2).Caption = "Paste"

Command1(3).Caption = "Del"

End Sub

Sub Command1_Click (Index As Integer)

' ActiveForm refers to the active form in the MDI form.

If TypeOf ActiveForm.ActiveControl Is TextBox Then

Select Case Index

Case 0	' Cut

' Copy selected text to Clipboard.

Clipboard.SetText ActiveForm.ActiveControl.SelText

' Delete selected text.

ActiveForm.ActiveControl.SelText = ""

Case 1	' Copy

' Copy selected text to Clipboard.

Clipboard.SetText ActiveForm.ActiveControl.SelText

Case 2	' Paste

' Put Clipboard text in text box.

ActiveForm.ActiveControl.SelText = Clipboard.GetText()

Case 3	' Delete

' Delete selected text.

ActiveForm.ActiveControl.SelText = ""

End Select

End If

End Sub


ActiveForm Property

See Also	Example1	Example2

Applies To

MDI form, Screen object.

Description

Specifies the form that is the active window,.  If an MDI form is active, or if an MDI form is referenced, specifies the active MDI child form.  Not available at design time; read-only at run time.

Usage

{mdiform|Screen}.ActiveForm

Remarks

Use the ActiveForm property to access a form's properties or to invoke its methods [image] for example, Screen.ActiveForm.Mousepointer = 4.

This property is especially useful in an MDI application where a button on a toolbar must initiate an action on a control in a MDI child form.  When a user clicks a Copy button on the toolbar, your code can reference the text in the active control on the MDI child form [image] for example, ActiveForm.ActiveControl.SelText.

When a control on a form has the focus, that form is the active form on the screen (Screen.ActiveForm).  In addition, an MDI form can have one child form that is the active form within the context of the MDI parent (MDIForm.ActiveForm).  The ActiveForm on the screen is not necessarily the same as the ActiveForm in the MDI form, such as when a dialog form is active.  For this reason, you should specify the MDI form with ActiveForm when there is a chance of a dialog being the ActiveForm.

Note	When an active MDI child form is not maximized, the title bars of both the parent form and the child form appear active.

If you plan to pass Screen.ActiveForm or MDIForm.ActiveForm to a procedure, you must declare the argument in that procedure with the generic type (As Form) rather than a specific form type (As MyForm) [image] even if ActiveForm always refers to the same type of form.

Data Type

Form


See Also

Help:

Activate, Deactivate Events

MDIChild Property

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


ActiveForm Property Example

The example prints the time on the currently active child form in an MDI form.  To try this example, create an MDI form, draw a picture box on it and draw a command button in the picture box.  In Form1, set the MDIChild property to True.  (You can also set AutoRedraw to True to keep text on the form even after covering it with another form.)  Paste the appropriate code into the Declarations section of each form and press F5.

' Copy this code into the MDI form.

Sub MDIForm_Load ()

Dim NewForm As New Form1	' Create new instance of Form1.

NewForm.Show

End Sub

' Copy this code into Form1.

Sub Command1_Click ()

' Print the time on the current form.
ActiveForm.Print "The time is " & Format(Now, "Long Time")
End Sub


Align Property

See Also	Example

Applies To

Picture box.

Description

Determines whether a picture box can appear in any size anywhere on a form, or whether it appears at the top or bottom of the form automatically sized to fit the form's width.

Usage

[form.]picturebox.Align[ = numericexpression ]

Setting

The Align property settings are:

Setting	Description

0	(Default in a non-MDI form) None [image] size and location can be set at design time or in code.  This setting is ignored if the picture box is on an MDI form.

1	(Default in an MDI form) Top [image] picture box is at the top of the form and its width is equal to the form's ScaleWidth property setting.

2	Bottom [image] picture box is at the bottom of the form and its width is equal to the form's ScaleWidth property setting.

Remarks

You can use the Align property to quickly create a toolbar or status bar at the top or bottom of a form.  As users change the size of the form, a picture box with Align set to 1 or 2 automatically resizes to fit the width of the form.

A picture box is the only standard control that can be placed on an MDI form.  The client area of an MDI form is defined by the space not covered by picture boxes.  When an MDI child form is maximized within the parent MDI form, it will not cover any picture boxes.

Data Type

Integer


See Also

Help:

Using MDI Features

ScaleHeight, ScaleWidth Properties

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Align Property Example

The example uses a picture box as a toolbar on an MDI form, with a command button to move the picture box from the top to the bottom of the form.  To try this example, create a new MDI form and set the MDIChild property of the other form to True.  Draw a picture box and put a command button on the picture box.  Paste the code into the Declarations section of Form1 and then press F5.

Sub Command1_Click ()

If Picture1.Align = 1 Then

Picture1.Align = 2	' Align to bottom of form.

Else
Picture1.Align = 1	' Align to top of form.

End If

End Sub


BackStyle Property

See Also

Applies To

Label, shape.

Description

Determines whether a label or the background of a shape is transparent or opaque.

Usage

[form.]{label|shape}.BackStyle[ = numericexpression ]

Setting

The BackStyle property settings are:

Setting	Description

0	Transparent [image] background color and any graphics are visible behind the control.

1	(Default) Opaque [image] the control's BackColor fills the control and obscures any color or graphics behind it.

Remarks

You can use the BackStyle property to create transparent controls when you are using a background color on a form or picture box, or when you want to place a control over a picture.  Use an opaque control when you want it to stand out on a busy background.

A control's BackColor property is ignored if BackStyle = 0.

Data Type

Integer


See Also

Help:

BackColor, ForeColor Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Chapter 16, "Displaying and Printing Information"


Columns Property

See Also	Example

Applies To

List box.

Description

Determines whether a list box scrolls vertically or horizontally.  If it scrolls horizontally, determines how many columns are displayed.

Usage

[form.]listbox.Columns

Setting

The Columns property settings are:

Setting	Description

0	(Default) Items are arranged in a single column and the list box scrolls vertically.

1 to n	Items are arranged in snaking columns, filling the first column, then the second column, and so on.  The list box scrolls horizontally and displays the specified number of columns.

Remarks

For horizontal-scrolling list boxes, the column width is equal to the width of the list box divided by the number of columns.

This property can't be set to zero or changed from zero at run time [image] that is, you can't change a multi-column list box to a single-column list box, or a single-column list box to a multi-column list box, at run time.  However, you can change the number of columns in a multi-column list box at run time.

Data Type

Integer


See Also

Help:

AddItem Method

Grid Control

List Property

ListCount Property

ListIndex Property

RemoveItem Method

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Columns Property Example

The example illustrates how the two different kinds of list boxes work when they contain the same data.  To try this example, paste the code into the Declarations section of a form that contains two list boxes.  .Set  the Columns property to 2 for List2.  Then press F5 and click the form

Sub Form_Load ()

Dim I	' Declare variable.

List1.Move 50, 50, 2000, 1750	' Arrange list boxes.

List2.Move 2500, 50, 3000, 1750

For I = 0 To Screen.FontCount -1	' Fill both boxes with

List1.AddItem Screen.Fonts(I)	' names of screen fonts.

List2.AddItem Screen.Fonts(I)

Next I

End Sub


Height, Width Properties

See Also	Example

Apply To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE Client, option button, picture box, Printer object, Screen object, shape, text box, vertical scroll bar.

Description

Determine the dimensions of an object.

Usage

{[form.][control.]|Printer.|Screen.}Height[ = numericexpression ]

{[form.][control.]|Printer.|Screen.}Width[ = numericexpression ]

Remarks

Measurements are calculated as follows:

Form [image] the external height and width of the form, including the borders and title bar.

Control [image] measured from the center of the control's border so that controls with different border widths align correctly.  These properties use the scale units of a control's container.

Printer object [image] the physical dimensions of the paper set up for the printing device; not available at design time and read-only at run time.

Screen object [image] the height and width of the screen; not available at design time and read-only at run time.

For a form, Printer object, and Screen object, these properties are always measured in twips.  For a form or control, the values for these properties change as the object is sized by the user or by code.  Maximum limits of these properties for all objects are system-dependent.

Use the Height, Width, Left, and Top properties for operations or calculations based on an object's total area, such as sizing or moving the object.  Use the ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth properties for operations or calculations based on an object's internal area, such as drawing or moving objects within another object.

Note	The Height property can't be changed for drive list boxes or for combo boxes whose Style property is 0 (Dropdown Combo) or 2 (Dropdown List).

Data Type

Single


See Also

Help:

Left, Top Properties

Move Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

Width Statement


Height, Width Properties Example

The example sets the size of a form to 75% of screen size, and centers the form when it is loaded.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Load ()

Width = Screen.Width * .75	' Set height of form.

Height = Screen.Height * .75	' Set width of form.

Left = (Screen.Width - Width) / 2	' Center form horizontally.

Top = (Screen.Height - Height) / 2	' Center form vertically.

End Sub


HelpContextID Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, list box, menu, OLE client, option button, picture box, text box, vertical scroll bar.

Description

Determines an associated context number for an object.  Used to provide context-sensitive Help for your application.

Usage

[form.][control.]HelpContextID[ = numericexpression ]

Remarks

For context-sensitive Help on an object in your application, you must assign the same context number to both the object and to the associated Help topic when you compile your Help file.

If you've created a Windows environment Help file for your application and set the application's HelpFile property, when a user presses the F1 key, Visual Basic automatically calls Help and requests the topic identified by the current context number.

The current context number is the value of HelpContextID for the object that has the focus.  If HelpContextID is 0, then Visual Basic looks in the HelpContextID of the object's container, and then that object's container, and so on.  If a non-zero current context number can't be found, the F1 key is ignored.

Note	Building a Help file requires the Microsoft Windows Help Compiler, which is available with the Visual Basic Professional Developer's Edition.

Data Type

Long integer


See Also

Help:

HelpFile Property

Visual Basic Professional Developer's Edition:

Help Compiler Guide


HelpFile Property

See Also	Example

Applies To

App object.

Description

Determines the name of the Microsoft Windows Help file for an application.

Usage

App.HelpFile[ = stringexpression ]

Remarks

If you've created a Microsoft Windows Help file for your application and set the application's HelpFile property, Visual Basic automatically calls Help when a user presses the F1 key.  If there is a context number in the HelpContextID property for either the active control or the active form, Help displays a topic corresponding to the current Help context; otherwise it displays the main contents screen.

Note	Building a Help file requires the Microsoft Windows Help Compiler, which is available with the Visual Basic Professional Developer's Edition.

Data Type

String


See Also

Help:

HelpContextID Property

Visual Basic Professional Developer's Edition:

Help Compiler Guide


HelpContextID, HelpFile Properties Example

The example uses topics in the Visual Basic Help file and demonstrates how to specify context numbers for Help topics.  To try this example, paste the code into the Declarations section of a form that contains a text box and a frame with an option button inside the frame.  Then press F5.  Once the program is running, move the focus to one of the components and press F1.

' Actual context numbers from the Visual Basic Help file.

Const winColorPalette = 21004	' Define constants.

Const winToolbox = 21001

Const winCodeWindow = 21005

Sub Form_Load ()

App.HelpFile = "vb.hlp"

Frame1.HelpContextID = winColorPalette

Text1.HelpContextID = winToolbox

Form1.HelpContextID = winCodeWindow

End Sub


HideSelection Property

See Also	Example

Applies To

Text box.

Description

Specifies whether selected text appears highlighted when a control loses the focus.  Read-only at run time.

Usage

[form.]textbox.HideSelection

Setting

The HideSelection property settings are:

Setting	Description

True	(Default) Selected text does not appear selected when the control loses the focus.

False	Selected text appears selected when the control loses the focus.

Remarks

You can use this property to indicate which text is selected while another form or a dialog box has the focus [image] for example, in a spell-checking routine.

Data Type

Integer (Boolean)


See Also

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


HideSelection Property Example

The example lets you select text in each form and change the focus between forms by clicking the title bar.  In one form, the selection will remain visible even when the form is not active.  To try the example, create two forms and draw a text box on each.  Set the MultiLine property to True for both text boxes, and set the HideSelection property to False for one of the text boxes.  Paste the code into the Declarations section of both form modules and press F5.

Sub Form_Load ()

Open "constant.txt" For Input As 1	' Load file into text box.

Text1.Text = Input$(LOF(1), 1)

Close 1

Form2.Visible = True	' Load Form2, if not already.

' Position forms side by side

Form1.Move 0, 1050, Screen.Width / 2, Screen.Height

Form2.Move Screen.Width / 2, 1050, Screen.Width / 2, Screen.Height

' Enlarge text box to fill form

Text1.Move 0, 0, ScaleWidth, ScaleHeight

End Sub


ItemData Property

See Also	Example

Applies To

Combo box, list box.

Description

This property is an array of long integer values with the same number of items as a control's List property.  Not available at design time.

Usage

[form.]{combobox|listbox}.ItemData(listindex)[ = numericexpression ]

Remarks

Use the ItemData property to associate a specific number with each item in a combo box or list box.  You can then use these numbers in code to identify the items.  For example, you can use an employee's identification number to identify each employee name in a list box.  When you fill the list box, also fill the corresponding elements in the ItemData array with the employee numbers.

A typical use of the ItemData property is for an index into an array of data structures associated with items in a list box.

Note	When you insert an item into a list with the AddItem method, an item is automatically inserted in the ItemData array as well.  However, the value is not reinitialized to zero; it retains the value that was in that position before you added the item to the list.  When you use the ItemData property, be sure to set its value when adding new items to a list.

Data Type

Long integer


See Also

Help:

AddItem Method

List Property

ListIndex Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ItemData and NewIndex Properties Example

The example fills a list box with employee names and fills the ItemData array with employee numbers using NewIndex to keep the numbers synchronized with the sorted list.  A label displays the name and number of an item when the user makes a selection.  To try this example, paste the code into the Declarations section of a form that contains a list box and a label.  Set the Sorted property for the list box to True.  Then press F5 and click the list box.

Sub Form_Load ()

' Fill List1 and ItemData array with

' corresponding items in sorted order.

List1.AddItem "Judy Phelps"

List1.ItemData(List1.NewIndex) = 42310

List1.AddItem "Chien Lieu"

List1.ItemData(List1.NewIndex) = 52855

List1.AddItem "Mauro Sorrento"

List1.ItemData(List1.NewIndex) = 64932

List1.AddItem "Cynthia Bennet"

List1.ItemData(List1.NewIndex) = 39227

End Sub

Sub List1_Click ()

' Append the employee number and the employee name

Msg = List1.ItemData(List1.ListIndex) & " "

Msg = Msg & List1.List(List1.ListIndex)

Label1.Caption = Msg

End Sub


KeyPreview Property

See Also	Example

Applies To

Form.

Description

Determines whether form keyboard events are invoked before control keyboard events.  The keyboard events are KeyDown, KeyUp, and KeyPress.

Usage

[form.]KeyPreview[ = {True|False} ]

Setting

The KeyPreview property settings are:

Setting	Description

True	The form receives keyboard events first, then the active control receives keyboard events.

False	(Default) The active control receives keyboard events; the form does not.

Remarks

You can use this property to create a keyboard-handling procedure for a form.  For example, when an application uses function keys, you'll want to process the keystrokes at the form level rather than writing code for each control that might receive keystroke events.

If a form has no visible and enabled controls, it automatically receives all keyboard events.

To handle keyboard events only at the form level and not allow controls to receive keyboard events, set KeyAscii to 0 in the form's KeyPress event, and set KeyCode to 0 in the form's KeyDown event.

Data Type

Integer (Boolean)


See Also

Help:

KeyDown, KeyUp Events

KeyPress Event

Programmer's Guide:

Chapter 3 "Creating and Using Controls"


KeyPreview Property Example

The example creates a form keyboard handler in the KeyDown event.  Each of the first four function keys presents a different message.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Once the program is running, press any one of the first four function keys.

' Values from CONSTANT.TXT

Const KEY_F1 = &H70

Const KEY_F2 = &H71

Const KEY_F3 = &H72

Const KEY_F4 = &H73

Sub Form_Load ()

KeyPreview = True

End Sub

Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)

Select Case KeyCode

Case KEY_F1: MsgBox "F1 is your friend."

Case KEY_F2: MsgBox "F2 could copy text."

Case KEY_F3: MsgBox "F3 could paste text."

Case KEY_F4: MsgBox "F4 could format text."

End Select

End Sub


MaxLength Property

See Also	Example

Applies To

Text box.

Description

Determines whether there is a limit to the length of the Text property.  The default for the MaxLength property is 0, indicating no maximum other than that created by memory constraints on the user's system for single line text boxes, and a maximum of about 32K for multiline text boxes.  Any number larger than 0 indicates the maximum number of characters.

Usage

[form.]textbox.MaxLength[ = numericexpression ]

Remarks

Use the MaxLength property to limit the number of characters a user can enter into a text box.

If text longer than MaxLength is assigned to a text box from code, no error occurs; however, only the maximum number of characters is assigned to the Text property and extra characters are truncated.  Changing this property doesn't affect the current contents of a text box but will affect any subsequent changes to the contents.

Data Type

Integer


See Also

Len Function

MultiLine Property


MaxLength Property Example

The example uses a numerical value in one text box to limit the length of text in the other text box.  To try this example, paste the code into the Declarations section of a form that contains two text boxes.  Make Text1 fairly large.  Then press F5.  Enter a number into Text2 and other text into Text1.

Sub Text1_Change ()

Text1.MaxLength = Text2.Text

End Sub


MDIChild Property

See Also	Example

Applies To

Form.

Description

Specifies whether a form will appear as an MDI child form inside an MDI form.  Read-only at run time.

Usage

form.MDIChild

Setting

The MDIChild property settings are:

Setting	Description

True	The form is an MDI child form and appears inside the parent MDI form.

False	(Default) The form is not an MDI child form.

Remarks

Use this property when creating a Multiple-Document Interface (MDI) application.  At run time, forms with this property set to True appear inside an MDI form.  An MDI child form can be maximized, minimized, and moved, all inside the parent MDI form.

When working with MDI child forms, keep the following in mind:

At run time, when an MDI child form is maximized, its caption is combined with that of the parent MDI form.

At design time, an MDI child form appears like any other form, since the form appears inside the parent form only at run time.  An MDI child form's icon in the Project window is different from icons for other kinds of forms.

MDI child forms can't be hidden and can't be modal.

The initial size and placement of MDI child forms is controlled by the Windows environment unless you specifically set it in the Form_Load procedure.

If an MDI child form is referenced before the parent is loaded, the parent MDI form is automatically loaded.  However, if the parent MDI form is referenced before loading an MDI child form, the child form is not loaded.

Note	When running under the Microsoft Windows 3.0 graphical environment, all MDI child forms have sizable borders, a Control-menu box, and Minimize and Maximize buttons, regardless of the settings of the BorderStyle, ControlBox, MinButton, and MaxButton properties.

Any reference to an MDI form, including reading or setting properties, causes the form to load and become visible.

Data Type

Integer (Boolean)


See Also

Help:

ActiveControl Property

ActiveForm Property

BorderStyle Property

ControlBox Property

MaxButton Property

MinButton Property

WindowList Property

Programmer's Guide:

Chapter 8, "Objects and Instances"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


MDIChild Property Example

The example presents an MDI form with an MDI child form and then creates another instance of the MDI child form.  To try this example, set MDIChild to True on Form1, and create an MDI form with the New MDI Form command on the File menu.  Copy the code into the Declarations section of the MDIForm and press F5 to run the program.

Sub MDIForm_Load ()

Dim NewForm As New Form1	' Declare new form.

NewForm.Show	' Show new form.

End Sub


MultiSelect Property

See Also	Example

Applies To

File list box, list box.

Description

Specifies whether a user can make multiple selections in a file list box or list box and how the multiple selections can be made.  Read-only at run time.

Usage

[form.]{filelistbox|listbox}.MultiSelect

Setting

The MultiSelect property settings are:

Setting	Description

0	(Default) Multiple selection is not allowed.

1	Simple multiple selection.  A click or the Spacebar selects or deselects an item in the list.  (Arrow keys move the pre-select focus.)

2	Extended multiple selection.  Shift+click or Shift+arrow key extends the selection from the previously selected item to the current item.  Ctrl+click selects or deselects an item in the list.

Data Type

Integer


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


MultiSelect, Selected Properties Example

The example fills a list box with the names of your screen fonts and illustrates how the MultiSelect property affects the behavior of a list box.  To try the example, create two list boxes and a command button on a form.  In the first list box, set MultiSelect to 1 or 2.  At run time, select several items in the first list and then click the command button.  All selected items appear in the second list box.  Run the example several times with different settings of the MultiSelect property.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Dim I	' Declare variable.

' Fill the list with screen font names.

For I = 0 To Screen.FontCount - 1

List1.AddItem Screen.Fonts(I)

Next I

End Sub

Sub Command1_Click ()

Dim I	' Declare variable.

' Clear all items from the list.

List2.Clear

' If an item is selected, add it to List2.

For I = 0 To List1.ListCount - 1

If List1.Selected(I) Then

List2.AddItem List1.List(I)

End If

Next I

End Sub


Name Property

See Also

Applies To

All forms and controls.

Description

Specifies the name used in code to identify an object.  Not available at run time.

Remarks

The default name for new objects is the kind of object plus a unique integer.  For example, the first new form is "Form1," a new MDI form is "MDIForm1," and the third text box you create on a form is "Text3."

An object's Name property must start with a letter and can be a maximum of 40 characters.  It can include numbers and underscore characters but can't include punctuation or spaces.  Forms can't have the same name as another global object such as Clipboard, Screen, or App.  However, unlike Visual Basic 1.0, a name can be the same as a reserved word, property name, or the name of another object, but this can create conflicts in your code.  See Chapter 6 in the Programmer's Guide, "Programming Fundamentals," for information on handling naming conflicts.

A form's Name property can be used with the Dim statement in code to create other instances of the form.

You can't have two forms at design time with the same name.  You can create an array of controls of the same type by setting the Name property to the same value.  For example, when you set the name of all option buttons in a group to "MyOpt," Visual Basic assigns unique values to the Index property of each control to distinguish it from others in the array.  Two controls of different types can't share the same name.

Note	Although the Name property is often used by Visual Basic as the default value for the Caption, LinkTopic, and Text properties, changing one does not affect the others.

Data Type

String


See Also

Help:

ActiveForm Property

Caption Property

Dim Statement

Index Property

LinkTopic Property

Me Reserved Word

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 6, "Programming Fundamentals"


NewIndex Property

See Also	Example

Applies To

Combo box, list box.

Description

Specifies the index of the item most recently added to a combo box or list box.  Not available at design time; read-only at run time.

Usage

[form.]{combobox|listbox}.NewIndex

Remarks

This property is useful with sorted lists when you need a list of values that correspond to each item in the ItemData property array.  As you add an item in a sorted list, Visual Basic inserts the item in the list alphabetically.  This property tells you where the item was inserted so that you can insert a corresponding value in the ItemData property at the same index.

NewIndex will return -1 if there are no items in the list or if an item has been deleted since the last item was added.

Data Type

Integer


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

MultiSelect Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


PasswordChar Property

See Also	Example

Applies To

Text box.

Description

Determines whether the characters typed by a user or placeholder characters are displayed in a text box; determines the character used as a placeholder.

Usage

[form.]textbox.PasswordChar[ = stringexpression ]

Remarks

Use this property to create a password field in a dialog box.  Although you can use any character, most applications for Windows use the asterisk (*) (Chr$(42)).

This property does not affect the Text property; it contains exactly what the user types or what was set from code.  Set PasswordChar to an empty string ("") or to Chr$(0) to display the actual text.  The default is an empty string.

You can assign any string to this property, but only the first character is significant; all others are ignored.

Data Type

String


See Also

Help:

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Password Property Example

The example illustrates how the PasswordChar property affects the way a text box displays text.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Then press F5 and click the form.  Each time you click the form, the text toggles between an asterisk password character and plain text.

Sub Form_Click ()

If Text1.PasswordChar = "" Then

Text1.PasswordChar = "*"

Else

Text1.PasswordChar = ""

End If

End Sub


Selected Property

See Also	Example

Applies To

File list box, list box.

Description

Determines the selection status of an item in a file list box or list box.  This property is an array of Boolean values with the same number of items as the List property.  Not available at design time.

Usage

[form.]{filelistbox|listbox}.Selected(index)[ = {True|False}]

Setting

The Selected property settings are:

Setting	Description

True	The item is selected.

False	(Default) The item is not selected.

Remarks

This property is particularly useful where users can make multiple selections.  You can quickly check which items in a list are selected.  You can also use this property to select or deselect items in a list from code.

If only one item is selected, you can use the ListIndex property to get the index of the selected item.  However, in a multiple selection, the ListIndex property returns the index of the item contained within the focus rectangle, whether or not the item is actually selected.

Data Type

Integer (Boolean)


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

ListIndex Property

MultiSelect Property

NewIndex Property

RemoveItem Method

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Shape Property

See Also	Example

Applies To

Shape.

Description

Determines the appearance of a shape control.

Usage

[form.]shape.Shape[ = numericexpression ]

Setting

The Shape property settings are:

Setting	Description

0	(Default) Rectangle

1	Square

2	Oval

3	Circle

4	Rounded Rectangle

5	Rounded Square

Data Type

Integer (Boolean)


See Also

Help:

BorderStyle Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Shape Property Example

The example illustrates the six possible shapes of the shape control.  To try this example, paste the code into the Declarations section of a form that contains an option button and a shape control.  On the option button, set Index to 0 to create a control array of one element.  Then press F5.  Click each option button to see each shape.

Sub Form_Load ()

Dim I	' Declare variable.

Option1(0).Caption = "Shape #0"

For I = 1 To 5  ' Create 5 instances of Option1.

Load Option1(I)

' Set the location of the new option button.

Option1(I).Top = Option1(I - 1).Top + 285

' Set the option button caption

Option1(I).Caption = "Shape #" & I

' Display the new option button

Option1(I).Visible = True

Next I

End Sub

Sub Option1_Click (Index As Integer)

Shape1.Shape = Index

End Sub


Shortcut Property

See Also

Applies To

Menu.

Description

Specifies a shortcut key for a menu control.  Not available at run time.

Remarks

Use this property to provide keyboard shortcuts for menu commands.  You can set this property in the Menu Design window or in the Properties window.  For a list of allowable shortcut keys, see the Shortcut list in the Menu Design window.

Note	In addition to shortcut keys, you can also assign access keys to commands, menus, and controls by using ampersands (&) in the Caption property.

Data Type

String


See Also

Help:

Caption Property

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Title Property

See Also

Applies To

App object.

Description

Determines the title of the application that appears in the Microsoft Windows Task Manager.  Can be changed at run time, but changes are not saved with the application.  Maximum length: 40 characters.

Usage

App.Title[ = stringexpression ]

Remarks

This property is available at design time in the dialog for the Make .EXE command on the File menu.

Data Type

String


See Also

Help:

Caption Property

Programmer's Guide:

Chapter 5, "Managing Projects"


TopIndex Property

See Also	Example

Applies To

File list box, list box.

Description

Determines which item in a file list box or list box appears in the topmost position.  The default is 0, or the first item in the list.  Not available at design time.

Usage

[form.]{filelistbox|listbox}.TopIndex[ = numericexpression ]

Remarks

Use this property to scroll through a file list box or list box without selecting an item.

If the Columns property is set to 0, the item appears at the topmost position if there are enough items below it to fill the visible portion of the list.

If Columns is greater than 0, the item's column moves to the leftmost position without changing its position within the column.

Data Type

Integer


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

MultiSelect Property

NewIndex Property

RemoveItem Method

Selected Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TopIndex Property Example

The example fills a list box with names of screen fonts and then scrolls through the list box when you click the form.  To try this example, paste the code into the Declarations section of a form that contains a list box.  Then press F5 and click the form.

Sub Form_Load ()

Dim I	' Declare variable.

For I = 0 To Screen.FontCount -1	' Fill list box with

List1.AddItem Screen.Fonts(I)	' screen font names.

Next I

End Sub

Sub Form_Click ()

Dim X	' Declare variable.

X = List1.TopIndex	' Get current index.

List1.TopIndex = List1.TopIndex + 5	' Reset topmost item.

If List1.TopIndex = X Then List1.TopIndex = 0

End Sub


WindowList Property

See Also	Example

Applies To

Menu.

Description

Specifies whether a menu maintains a list of the current MDI child windows in an MDI form.  Read-only at run time.

Usage

menuname.WindowList

Setting

The WindowList property settings are:

Setting	Description

True	The menu maintains a list of open windows and displays a check mark next to the currently active window.  Users can click a window name to activate that window.

False	(Default) The menu does not maintain a list of open windows.

Remarks

Many Multiple-Document Interface (MDI) applications, such as Microsoft Excel and Microsoft Word for Windows, have a Window menu containing a list of open MDI child windows.  This property enables you to add this functionality to your application.

Only one menu control on a form can have a WindowList.

When you set WindowList to True on a menu control, the WindowList menu structure is appended to the menu items indented below it.

Data Type

Integer (Boolean)


See Also

Help:

Caption Property

Creating a Menu Bar

Menu Design Window

Programmer's Guide:

Chapter 4, "Menus and Dialogs"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


WindowList Property Example

The example creates some menu commands, illustrates the WindowList menu functionality, and shows how to enable your users to add new forms to an MDI application.  To try this example, create an MDI form with the New MDI Form command on the File menu.  On Form1, set the MDIChild property to True and create a menu named "File."  On your Window menu, click the WindowList check box.  On your File menu, create a "New" command, set Name to "FileMenu," and set Index to 0 (to create a control array).  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

FileMenu(0).Caption = "&New"	' Set access key in caption.

Load FileMenu(1)	' Create new menu item.

FileMenu(1).Caption = "-"	' Set separator.

Load FileMenu(2)	' Create new menu item.

FileMenu(2).Caption = "E&xit"	' Set caption and access key.

End Sub

Sub FileMenu_Click (Index As Integer)

Select Case Index

Case 0	' New.

Dim NewForm As New Form1	' Create a duplicate of Form1.

' Load NewForm and set a unique caption.

NewForm.Caption = "Untitled" + Forms.Count

Case 2	' Exit.

End	' End the program.

End Select

End Sub


WordWrap Property

See Also	Example

Applies To

Label.

Description

Determines whether a label with its AutoSize property set to True expands vertically or horizontally to fit the text specified in its Caption property.

Usage

[form.]label.WordWrap[ = {True|False} ]

Setting

The WordWrap property settings are:

Setting	Description

True	The text wraps; the label expands or contracts vertically to fit the text and the size of the font.  The horizontal size does not change.

False	(Default) The text does not wrap; the label expands or contracts horizontally to fit the length of the text and vertically to fit the size of the font and the number of lines.

Remarks

Use this property to determine how a label displays its contents.  For example, a graph that changes dynamically might have a label containing text that also changes.  To maintain a constant horizontal size for the label and allow for increasing or decreasing text, you would set the WordWrap and AutoSize properties to True.

If you want a label to expand only horizontally, set WordWrap to False.  If you do not want the label to change size, set AutoSize to False.

Note	If AutoSize is False, the text always wraps, regardless of the size of the label or the setting of the WordWrap property.  This may obscure some text, since the label does not expand in any direction.

Data Type

Integer (Boolean)


See Also

Help:

AutoSize Property

Caption Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


WordWrap Property Example

The example puts text into two labels and uses the WordWrap property to illustrate their different behavior.  To try this example, paste the code into the Declarations section of a form that contains two labels.  Then press F5 and click the form to toggle the WordWrap property.

Sub Form_Load ()

Dim Author1, Author2, Quote1, Quote2	' Declare variables.

Label1.AutoSize = True	' Set AutoSize.

Label2.AutoSize = True

Label1.WordWrap = True	' Set WordWrap.

Quote1 = "I couldn't wait for success, so I went on without it."

Author1 = "  - Jonathan Winter"

Quote2 = "Logic is a system whereby one may go wrong with confidence."

Author2 = "  - Charles Kettering"

Label1.Caption = Quote1 & Chr(10) & Author1

Label2.Caption = Quote2 & Chr(10) & Author2

End Sub

Sub Form_Click ()

Label1.Width = 1440	' Set width to 1 inch in twips.

Label2.Width = 1440

Label1.WordWrap = Not Label1.WordWrap	' Toggle WordWrap property.

Label2.WordWrap = Not Label2.WordWrap

End Sub


X1, Y1, X2, Y2 Properties

See Also	Example

Apply To

Line.

Description

Determine the coordinates of the starting point (X1, Y1) and ending point (X2, Y2) of a line control.  The horizontal coordinates are X1 and X2; the vertical coordinates are Y1 and Y2.

Usage

[form.]line.X1[ = numericexpression ]

[form.]line.Y1[ = numericexpression ]

[form.]line.X2[ = numericexpression ]

[form.]line.Y2[ = numericexpression ]

Remarks

Use these properties to dynamically extend a line from one point to another at run time.  For example, you can show the relationships of items in one list to items in another list, or connect points on a map.

Data Type

Single


See Also

Help:

Left, Top Properties

Line Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


X1, Y1, X2, Y2 Properties Example

The example is an animated line that walks down the form when you click the form.  To try this example, paste the code into the Declarations section of a form that contains a timer and a line control.  Then press F5 and click the form.

Sub Form_Load ()

Timer1.Interval = 100	' Set Timer interval.

' Position the line near the upper left corner.

Line1.X1 = 100

Line1.Y1 = 100

Line1.X2 = 500

Line1.Y2 = 300

End Sub

Sub Form_Click ()

Timer1.Enabled = True	' Start the timer.

End Sub

Sub Timer1_Timer ()

Static Odd	' Declare variable.

If Odd Then

Line1.X2 = Line1.X2 + 250

Line1.Y2 = Line1.Y2 + 600

Else

Line1.X1 = Line1.X1 + 250

Line1.Y1 = Line1.Y1 + 600

End If

Odd = Not Odd	' Toggle the value.

' If the line is off the form, start over.

If Line1.Y1 > ScaleHeight Then

Timer1.Enabled = False	' Wait for new click.

Line1.X1 = 100

Line1.Y1 = 100

Line1.X2 = 500

Line1.Y2 = 300

Odd = False

End If

End Sub


Saving and Loading Forms in ASCII Format

See Also

Visual Basic can save and load both binary format and ASCII format forms.  Binary format forms load quickly but you can edit them only in Visual Basic.  ASCII format forms take longer to load but you can edit them with any text editor.  Visual Basic saves forms in binary format by default.  You can load binary files in Visual Basic only if their binary format is recognized by the current or previous version of Visual Basic.

To always save all new forms and modules as ASCII text

1.	From the Options menu, choose Environment.

2.	In the list, select Default Save As Format, and in the Setting combo box, choose Text.

To save an individual form as ASCII text

1.	In the Project window, select the file you want to save.

2.	From the File menu, choose Save File As.

3.	In the Save File As dialog box, check the Save As Text check box.

4.	Type a new name for the file if necessary and choose OK.

Once you save a form as text, that form is saved in ASCII text format (for example, when you choose Save from the File menu) until you use the Save As command to save it as binary.

To load an ASCII format form

From the File menu, choose the Add File command and specify the file name.

If an error occurs while loading an ASCII form file, Visual Basic writes an error message to a file with the base name of the form file and the extension .LOG, and displays a message on screen when it has finished loading the file.

Note	Don't confuse saving and loading ASCII format form files with the Save Text and Load Text commands on the File menu.  Use these commands to save and load nonform code modules or to save only the procedures in a form file as text.  If you create separate files using the Save Text command, those files will not be included in the project.


See Also

Help:

Environment Command (Options Menu)

Load and Save Text Commands

Save File Command

Saving Your Work

Programmer's Guide:

Appendix A, "ASCII File Format"


Setting Options

See Also

You can use the commands on the Options menu to set new preferences or reset default values for the programming environment or for specific projects.  Programming environment options include the foreground and background colors in a Code window, the number of spaces for the Tab key in a Code window, syntax checking, and whether variables must be declared before being referenced.  You can also set the number of horizontal and vertical grid lines on forms in design mode, and you can specify whether grid lines are visible and whether controls snap to the grid lines when placed on a form.

To set preferences for the programing environment

1.	From the Options menu, choose Environment.

2.	In the Setting combo box, select an option.

3.	In the text box portion of the Setting combo box, enter a new value.

4.	Choose OK.

Preferences for specific projects include a command-line argument setting to allow testing of command-line arguments for the application, specification of the name of the startup form for the application, and a specification for the application's Help file.

To set preferences for a specific project

1.	From the Options menu, choose Project.

2.	In the Setting combo box, select an option.

3.	In the text box portion of the Setting combo box, enter a new value.

4.	Choose OK.

You can also restore one, many, or all options to their original default values.

To restore selected preferences to default values

1.	From the Options menu, choose Environment or Project.

2.	In the Setting combo box, select an option or multiple options.

3.	Choose Reset.

To restore all preferences to default values

1.	From the Options menu, choose Environment or Project.

2.	Choose Reset All.


See Also

Help:

Environment Command (Options Menu)

Project Command (Options Menu)

Programmer's Guide:

Chapter 2, "Creating Your First Visual Basic Application"


Using MDI Features

See Also

Visual Basic's multiple-document interface (MDI) features enable you to create applications in which a single parent form (an MDI form) provides a background for multiple child forms (forms whose MDIChild property is True).  When you create MDI applications, keep the following in mind:

When an MDI child form is the startup form, the MDI form is loaded automatically; but MDI child forms are loaded only when specified as the startup form, when referenced in code, or when specified in a Load statement.

The menu bar designed for an MDI child form is displayed on the MDI form at run time when the MDI child form is active, even though it appears on the child form at design time.

The only controls you can place on an MDI child form are a picture box or a custom control that has an Align property.  However, you can place other controls in the picture box.  Typically, you use the picture box to create a toolbar.  A picture box on an MDI form has the same width as the ScaleWidth of the MDI form, but it can have any height up to the ScaleHeight of the form.  The picture box must be aligned to the top or bottom of the MDI form client area.

If you want several MDI child forms in an MDI application to function identically, you can use multiple instances of a single form type, or an array of forms of a single type, instead of designing different child forms.  MDI child forms can be loaded or instantiated dynamically at run time using the Dim statement.  After creating a new instance of a form, you can change that instance's properties without affecting other forms.

Use the Me keyword to use common event procedures to reference the currently active instance of a form or the currently active form array element.  Similarly, the ActiveForm property of the MDI form specifies the MDI child form that has the focus (or that was most recently active).

Check the WindowList check box in the Menu Design window of the MDI form or an MDI child form when you want that menu control to display a list of open child forms at run time.

Use the Arrange method to rearrange child forms and their icons.


See Also

Help:

MDIChild Property

Me

Programmer's Guide:

Chapter 8, "Objects and Instances"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Using Custom Controls

See Also

You can use custom controls in your applications by loading them into the programming environment using the Add File command on the File menu, or by specifying their definition files (files with a .VBX extension) in a project's .MAK file.  For example, Visual Basic has a default project file called AUTOLOAD.MAK that includes two custom-control file specifications [image] GRID.VBX for the grid control, and OLECLIENT.VBX for the OLE client control.  When Visual Basic starts with no other file specification, the default AUTOLOAD.MAK project is loaded and the icons for the grid and OLE client controls appear at the bottom of the Toolbox.  You use custom controls the same way as other controls in Visual Basic.


See Also

Help:

Grid Control

OLE Client Control

Programmer's Guide:

Chapter 13, "Using the Grid Control"

Chapter 21, "Object Linking and Embedding (OLE)"


Using Watch Expressions

See Also

There are two ways to watch, or monitor, expressions in Visual Basic.  You can simply watch the value of the expression in the Debug window, or you can suspend program execution when the expression is true or changed.

When you watch the value of an expression, you generally set a breakpoint in a procedure in which you want to know the expression's value, and then use the Instant watch command to see the expression's value when program execution is suspended in that procedure.  When you use Instant watch, you have the option of also placing the expression in the Debug window.

You can also use the last two options in the Watch Type group to suspend application execution either when an expression becomes nonzero or each time the expression's value changes from zero to nonzero or from nonzero to zero.  Note that the term "true" when used with watchpoints refers to the logical (nonzero) state true, rather than to the bitwise complement of zero (that is, Not False, expressed as the intrinsic constant True (whose value is always -1).

For example, if you choose the Break When Expression is True option for a variable named MyVar in a procedure, program execution is suspended as soon as MyVar acquires a nonzero value.  However, if you choose it for the expression MyVar > 5, execution is not suspended until the expression MyVar > 5 evaluates to True.  Note that a simple string variable cannot be evaluated by itself; it must be used in a comparative expression like StrVar$ <> "" or be evaluated, as in the function call Len(StrVar$), in order for a watchpoint to suspend execution when it changes from an empty (zero length) to nonempty state.

The Context option for an expression can be no wider than the scope of the components of the expression.  For example, local variables can have only Procedure context.  Expressions whose components are defined at form or module level can have Procedure or Form/Module context, and globally scoped expressions can have any context.


See Also

Help:

Edit Watch Command

Programmer's Guide:

Chapter 9, "Debugging"


Using Dynamic Data Exchange (DDE)

See Also

Visual Basic's DDE features enable your applications to directly and continuously exchange data with other Windows-based applications that support DDE.  These data exchanges are called conversations.  You start data exchanges by establishing DDE links, which you can create at design time or run time.  Links you create at design time (see Creating a DDE Source or Destination Link) are simplest because they are automatically reestablished whenever the application is run.  However, when you create links at design time, the application with which you communicate must contain Copy and PasteLink commands.  Similarly, when you run the Visual Basic project at a later time, the other application must be available or an error will occur.  With design-time links, all updates to controls are made immediately and automatically whenever a data change occurs.  Links that are established at design time may fail at run time if the other application is unable to refresh them.

Links created at run time are more flexible, but they require you to write enabling code that sets the properties of the controls involved in the data exchange.  There are several advantages to creating links in code:

The other applications do not need Copy and PasteLink commands.

Your application can start the other application before initiating a conversation.

You can trap and handle errors.

When DDE links are created at run time, your application can choose when updates of data between linked controls actually occur.


See Also

Help:

DDE Example Between Visual Basic and Excel for Windows

DDE Example Between Visual Basic and Word for Windows

Example of Source/Destination DDE Between Visual Basic Applications

LinkClose Event

LinkError Event

LinkExecute Event

LinkExecute Method

LinkItem Property

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkPoke Method

LinkRequest Method

LinkSend Method

LinkTimeOut Property

LinkTopic Property

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


Visual Basic Menus


Visual Basic Menus

File Menu

Edit Menu

View Menu

Run Menu

Debug Menu

Options Menu

Window Menu

Help Menu


File Menu

New Project

Open Project

Save Project

Save Project As

New Form

New MDI Form

New Module

Add File

Remove File

Save File

Save File As

Load Text

Save Text

Print

Make EXE File

Exit


Edit Menu

Undo

Redo

Cut

Copy

Paste

Paste Link

Delete

Find

Find Next

Find Previous

Replace

Bring To Front

Send To Back

Align To Grid


View Menu

Code

New Procedure

Next Procedure

Previous Procedure

Procedure Definition

Toolbar


Debug Menu

Add Watch

Instant Watch

Edit Watch

Calls

Single Step

Procedure Step

Toggle Breakpoint

Clear All Breakpoints

Set Next Statement

Show Next Statement


Run Menu

Start

Continue

Break

End

Restart


Options Menu

Environment

Project


New Project Command (File Menu)

See Also

Creates a new project.

You can have only one project open at a time in Visual Basic.  When you create a new project, Visual Basic prompts you to save your work in the current project, then closes all open files in the current project and creates a new one.  To specify default settings for new projects, you can modify the AUTOLOAD.MAK project with the forms, modules and custom controls you want for all new projects.


See Also

Help:

Open Project Command (File Menu)

Project Command (Options Menu)

Project Command (Window Menu)

Save Project, Save Project As... Commands (File Menu)

Programmer's Guide:

Chapter 5, "Managing Projects"


Open Project Command (File Menu)

See Also

Closes the current project, if any, and loads an existing project.

Toolbar shortcut:

Dialog Box Options

Option	Description

File Name	Type or select a project file from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the project is stored if different from your current path.  (The current path is displayed above this box.)

Drives	Select a drive from the list.

List Files of Type	Select a file type from the list.  Files of the selected type will appear in the list box.

OK	Opens the selected file.

Cancel	Closes the dialog box without opening a file.


See Also

Help:

New Project Command (File Menu)

Project Command (Options Menu)

Project Command (Window Menu)

Save Project, Save Project As... Commands (File Menu)

Programmer's Guide:

Chapter 5, "Managing Projects"


Save Project, Save Project As... Command (File Menu)

See Also

Saves the current project (.MAK) and all forms and modules in the current project.  If you have any new forms or modules, you'll be prompted to save them.

Forms and modules are stored in text format or in binary format.  You specify the format in the Save Project As dialog, or with the Project command on the Options menu.

Toolbar shortcut:

Dialog Box Options for Save Project As...

Option	Description

File Name	Type a file name for the project or accept the default file name.  Unless you specify otherwise, Visual Basic automatically adds the default file-name extension .MAK.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list.  Files of the selected type will appear in the list box.

Drives	Select a drive from the list.

OK	Saves the project under the specified name.

Cancel	Closes the dialog box without saving the project.

If you type a new name for an existing project, Visual Basic creates a new project. The earlier version of the file remains under its earlier name.

If you type the name of an existing project, Visual Basic displays a message warning you that you'll be overwriting an existing file.  Choose:

OK	To replace the existing file.

Cancel	To close the dialog box without saving the file.


See Also

Help:

New Project Command (File Menu)

Open Project Command (File Menu)

Project Command (Options Menu)

Project Command (Window Menu)

Saving Your Work

Programmer's Guide:

Chapter 5, "Managing Projects"


New Form, New MDI Form, New Module Commands (File Menu)

See Also

Creates a new form, a new multiple-document interface (MDI) form, or a new module, and adds it to your project.  Because a project can have only one MDI form, the New MDI Form command is unavailable if a project already has an MDI form.

New Form toolbar shortcut:

New Module toolbar shortcut:


See Also

Help:

MDIChild Property

New Project Command (File Menu)

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Add File Command (File Menu)

See Also

Adds an existing form, module, or custom control file to your project.  You can use a form or module in any number of projects.

Dialog Box Options

Option	Description

File Name	Type or select a file name from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list:

VB Files (*.FRM; *.BAS; *.VBX) [image] lists all valid Visual Basic file types.

Form Files (*.FRM) [image] lists all forms.

Basic Files (*.BAS) [image] lists all modules.

Custom Controls (*.VBX) [image] lists all custom controls.

Drives	Select a drive from the list.

OK	Adds the file to the project.

Cancel	Closes the dialog box without adding the file to the project .


See Also

Help:

Remove File Command (File Menu)

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Remove File Command (File Menu)

See Also

Removes the active form, module, or custom control file from your project.

Removing a file does not delete the file from your disk.  The file remains in all the other projects to which it has been added.

Files that have been removed from a project remain stored on your hard disk until you delete them, following standard procedures for your operating system.

When removing a form, module, or custom control from a project, make sure the remaining code does not refer to the removed file.


See Also

Help:

Add File Command (File Menu)

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Save File, Save File As... Command (File Menu)

See Also

Saves the active form or module to your disk with a name you specify.  The Save File command displays the Save As dialog box if no file name has been specified.

The dialog box enables you to specify a new name for a form, MDI form, or module.

Dialog Box Options for Save File As...

Option	Description

File Name	Type a file name or accept the default.  Unless you specify otherwise, Visual Basic automatically adds the default file-name extension .MAK for projects, .FRM for forms, and .BAS for modules.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list:

All Files (*.*) [image] list files of all types.

Form Files (*.FRM) [image] list all form files.

Basic Files (*.BAS) [image] list all modules.

Drives	Select a drive from the list.

Save As Text	Select to save the current file in text format.  If not selected, files are saved in binary format.  You can set the Default Save As Format for all files with the Environment command on the Options menu.

OK	Saves the file under the specified name.

Cancel	Closes the dialog box without saving the file.

If you type a new name for an existing file, Visual Basic creates a new file.  The old version of the file remains on your disk with the old name.

If you type the name of an existing file, Visual Basic displays a message warning you that you'll be overwriting an existing file.  Choose:

OK	To replace the existing file.

Cancel	To close the dialog box without saving the file.


See Also

Help:

Add File Command (File Menu)

New Form, New MDI Form, New Module Commands (File Menu)

Saving Your Work

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Load Text, Save Text Commands (File Menu)

See Also

Load Text [image] use to specify a text file from which you load code into a Visual Basic Code window.

Save Text [image] use to save the code in the current form, MDI form, or module as a text file.  To save a form or MDI form as text, including all property settings, choose the Save File As command from the File Menu.

Dialog Box Options

Options	Description

File Name	Type or select a file name from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored or where you want to store the file if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list:

Text Files (*.TXT) [image] lists all text files.

Basic Files (*.BAS) [image] lists all modules.

All Files (*.*) [image] lists files of all types.

Drives	Select a drive from the list.

Replace	Replaces all the text in the active module with the code you're loading.

Merge	Adds the text you're loading to the code in the active module at the current insertion point without deleting existing code.

New	Creates a new module with the text you're loading.

Cancel	Closes the dialog box without loading the code.


See Also

Help:

Project Command (Options Menu)

Save File, Save File As... Commands (File Menu)

Save Project, Save Project As... Commands (File Menu)

Saving Your Work

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Print Command (File Menu)

See Also

Prints forms and code to the printer specified in the Microsoft Windows Control Panel.

Dialog Box Options

Option	Description

Current 	Prints the active form or the code in the active Code window.

All	Prints all forms or all code in your application.

Form	Prints the current form or all forms in your application.

Form Text	Prints the text representation for the current form or all forms in your application.  Use this feature to print out all form and control properties and their values.

Code	Prints the code for the current file or for all forms and modules in your application.

OK	Prints your selection.

Cancel	Closes the dialog box without printing.


See Also

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Make EXE File Command (File Menu)

See Also

Creates an executable application by combining the forms and modules in a project into a single executable file.

An executable file runs without invoking Visual Basic.  To run an executable file, the run-time file VBRUN200.DLL must be in a directory on the user's path.

This command does not affect the project files.  You can still work with your original files without affecting the executable file.

Dialog Box Options

Options	Description

File Name	Type the file name for the executable file or accept the default.  Unless you specify otherwise, Visual Basic automatically adds the default file-name extension .EXE to an executable file.

Directories	Select a directory from the list.  Select the drive or directory where the file is to be stored if different from your current path.  (Your current path is displayed above this box.)

Drives	Select a drive from the list.

Application Title	Specify the title for your application or accept the default (the project name).  This title will appear in the Microsoft Windows Task Manager when the executable file is running.

Icon	Shows the icon that the Microsoft Windows Program Manager displays for the application.  The default icon is the icon for the startup form.

Use Icon From	Select an icon from among those you've assigned to the Icon property for forms in the project.

OK	Creates an executable version of your application.

Cancel	Closes the dialog box without making an executable file.


See Also

Help:

Icon Library

Icon Property

Programmer's Guide:

Chapter 5, "Managing Projects"


Exit Command (File Menu)

See Also

Closes the current project and quits Visual Basic.  If you try to quit Visual Basic before saving changes to your work, you'll be prompted to save your work first.

Mouse shortcut: double-click the Control-menu box.  Keyboard shortcut: Alt+F4.


See Also

Programmer's Guide:

Chapter 1, "Introduction"


Redo, Undo Commands (Edit Menu)

See Also

Undo [image] reverses the last editing action, such as typing text in the code editor or deleting controls.  When you delete one or more controls, you can use the Undo command to restore the controls and all their properties except for the TabIndex property, which cannot be restored.  TabIndex is reset to the end of the Tab order when using Undo.  For forms, Undo is unavailable if the form has been edited since the last control deletion.

Keyboard shortcut: Ctrl+Z.

Redo [image] restores the last text editing Undo actions if no other actions occur since the last Undo.

Keyboard shortcut: Ctrl+Backspace.

For text edits, you can use Undo and Redo to restore up to twenty editing actions.

These commands are unavailable if there was no previous editing action, or if any other action has been performed after the last editing action.


See Also

Programmer's Guide:

Chapter 1, "Introduction"


Cut, Copy, Paste, and Delete Commands (Edit Menu)

See Also

Cut [image] removes the selected control or text and places it on the Clipboard.

Keyboard shortcut: Ctrl+X.

Copy [image] copies the selected control or text to the Clipboard.

Keyboard shortcut: Ctrl+C.

Paste [image] inserts a control or text that has been copied to the Clipboard.  Text is placed at the insertion point.  Pasted controls are placed at the upper left of the active form.

When you paste a control, it has the same properties and control Name as the control you copied.  You can keep the same name and create a control array, or paste the control with a different name.

Keyboard shortcut: Ctrl+V.

Delete [image] erases the currently selected control or text.

To remove a form or module from a project without deleting it from your disk, choose the Remove File command from the File menu.

To delete a file from your disk, follow standard deletion procedures for your operating system.

Keyboard shortcut: Del.


See Also

Help:

Remove File Command (File Menu)

Programmer's Guide:

Chapter 1, "Introduction"


Paste Link Command (Edit Menu)

See Also

Inserts Clipboard contents copied from another Windows-based application.  It also creates a link with that application to update the copied data automatically.

This command is unavailable unless Visual Basic determines that the Clipboard contents came from an application that can transfer data to Visual Basic and the destination control of the link is capable of having a DDE link.


See Also

Help:

Creating a DDE Source or Destination Link

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


Find, Find Next, Find Previous Commands (Edit Menu)

See Also

Find [image] searches code in the project for specified text.

Find Next [image] searches code in the project for the next occurrence of the text you specified.

Keyboard shortcut: F3.

Find Previous [image] searches code in the project in reverse order for a previous occurrence of the text you specified.

Keyboard shortcut: Shift+F3.

If a search is successful, the dialog box closes and Visual Basic selects the located text.  If no match is found, Visual Basic displays a message stating that the text was not found.

Dialog Box Options

Option	Description

Find What	Type the text you want to search for.  If any text is selected when you choose the command, this text is displayed in the text box.  If no text is selected, the word at the current insertion point is displayed.

Search Current Procedure	Searches only the current procedure.

Search Current Module	Searches only the current module.

Search All Modules	Searches all the code in your project.

Match Whole Word Only 	Searches for the full word by itself and not as part of another word.

Use Pattern Matching	Searches using pattern matching characters.

OK	Starts the text search.

Cancel	Closes the dialog box without performing the search.


See Also

Help:

Finding a Procedure

Programmer's Guide:

Chapter 1, "Introduction"

Chapter 9, "Debugging"


Replace Command (Edit Menu)

See Also

Searches code in the project for the specified text and replaces it with new text.

Dialog Box Options

Option	Description

Find What	Type the text you want to search for.  If any text is selected when you choose the command, this text is displayed in the text box.  If no text is selected, the word at the current insertion point is displayed.

Replace With	Type the new text.

Search Current Procedure	Searches only the current procedure.

Search Current Module	Searches only the code in the current module.

Search All Modules	Searches all the code in your project.

Syntax Checking On	Checks the syntax after making the replacement.

Match Whole Word Only 	Searches for the full word by itself and not as part of another word.

Use Pattern Matching	Searches using pattern matching characters.

Verify	Confirms before replacing the search text with the replacement text.

Replace All	Replaces all occurrences of the search text with the replacement text without stopping for confirmation.  If a syntax error is found while the Syntax Checking option is selected, the search ends after the error is found, and possibly before any text has been replaced.

Cancel	Closes the dialog box without replacing text.

If you select the Verify box, Visual Basic displays a message when the search text is found asking you to confirm that you want the text replaced.

Yes	Replaces the selected text, then continues the search.

No	Continues the search without changing the selected text.

Cancel	Cancels the search.


See Also

Help:

Find, Find Next, Find Previous Commands (Edit Menu)

Replacing Text in Code

Programmer's Guide:

Chapter 9, "Debugging"


Bring To Front, Send To Back Commands (Edit Menu)

See Also

Bring To Front [image] moves the selected control to the front of all other objects.

Send To Back [image] moves the selected control behind all other objects.

Note	These commands work only with selected controls at design time.  In code, you can use the ZOrder method to move forms to the front or back of other forms, and controls to the front or back of other controls.


See Also

Help:

ZOrder Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Align To Grid Command (Edit Menu)

See Also

Specifies whether the selected controls on a form automatically align to the grid.

To have all controls automatically align to the grid, use the Environment command on the Options menu.


See Also

Help:

Environment Command (Options Menu)


Code Command (View Menu)

See Also

Displays or activates the Code window for the current form or module.

Keyboard shortcut: F7.


See Also

Help:

Guidelines for Entering and Editing Code

Programmer's Guide:

Chapter 6, "Programming Fundamentals"

Chapter 9, "Debugging"


New Procedure Command (View Menu)

See Also

Creates a new Sub or Function procedure.

Dialog Box Options

Options	Description

Name	Type a name for the new procedure.

Sub	Creates a new Sub procedure.

Function	Creates a new Function procedure.

OK	Creates the procedure in the Code window.

Cancel	Closes the dialog box without creating a new procedure.


See Also

Help:

Guidelines for Entering and Editing Code

Next Procedure, Previous Procedure Command (View Menu)

Programmer's Guide:

Chapter 6, "Programming Fundamentals"


Next Procedure, Previous Procedure Commands (View Menu)

See Also

Next Procedure [image] displays the next procedure in the current form or module.

Keyboard shortcut: Ctrl+Down Arrow.

Previous Procedure [image] displays the previous procedure.

Keyboard shortcut: Ctrl+Up Arrow.


See Also

Help:

Guidelines for Entering and Editing Code

New Procedure Command (View Menu)

Programmer's Guide:

Chapter 6, "Programming Fundamentals"

Chapter 9, "Debugging"


Procedure Definition Command (View Menu)

See Also

Displays the code for a procedure called from within another procedure.  For example, in the Form_Load procedure, you might have a call to the Click event procedure for a menu item using mnuOpen_Click.  If you click this code in the Form_Load procedure and then choose the Procedure Definition command, the Code window displays the code for your mnuOpen_Click procedure.


See Also

Help:

Next Procedure, Previous Procedure Commands (View Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Toolbar Command (View Menu)

See Also

Displays or removes the toolbar.  A check mark appears in front of this command when the toolbar is visible.


See Also

Help:

Menu Bar and Toolbar

Programmer's Guide:

Back cover.


Start Command (Run Menu)

See Also

Runs the application from the beginning (either a startup form or Sub Main as set with the Project command on the Options menu).  All forms being designed are closed, variables are initialized, and the startup form (if any) is loaded.

This command is available only at design time.

Toolbar button:   Keyboard shortcut: F5.


See Also

Help:

Break Command (Run Menu)

Continue Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Break Command (Run Menu)

See Also

Stops execution of a program while it's running and switches to break mode.  If a statement is being executed when you choose this command, that statement is displayed in the Code window with a thin-line border around it, and highlighted in the colors you set with the Environment command on the Options menu.  If the application is waiting for events in the idle loop (that is, no statement is being executed), no statement is highlighted until an event occurs.

Some editing changes made during break mode may require you to restart your program for the changes to take effect.

This command is available only at run time.

Toolbar button:   Keyboard shortcut: Ctrl+Break.


See Also

Help:

Continue Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Continue Command (Run Menu)

See Also

Continues executing your application after any kind of interruption.  An interruption can be caused by run-time errors, a Stop statement, a breakpoint in your code, choosing the Break command, or pressing Ctrl+Break while your program is running.

Choosing the Continue command doesn't restart the application.  It continues execution after the last successfully executed statement.

This command is available only in break mode.

Toolbar button:   Keyboard shortcut: F5.


See Also

Help:

Break Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


End Command (Run Menu)

See Also

Stops running the application and returns to design time.

This command is available during run time and while in break mode.

Toolbar shortcut:


See Also

Help:

Break Command (Run Menu)

Continue Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Restart Command (Run Menu)

See Also

Resets application variables to their initial value and starts running the application from the beginning.  Use the Restart command to reinitialize the variables before continuing an application that has been interrupted or halted.

If you choose this command while a program is running or in break mode, execution is terminated and then restarted.

This command is available during run time and break mode.

Keyboard shortcut: Shift+F5.


See Also

Help:

Break Command (Run Menu)

Continue Command (Run Menu)

End Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Add Watch Command (Debug Menu)

See Also

Displays a dialog box in which you enter a watch expression.  The expression can be any valid Basic expression.  Watch expressions are updated in the upper pane of the Debug window each time you enter break mode.

When selecting a context for a watch expression, use the narrowest scope that fits your needs.  Selecting Global or Form/Module could slow your program considerably, since Visual Basic evaluates the expression after executing each line of code.  Selecting Procedure for a context will affect execution only while the selected procedure is in the list of active procedure calls, which you can see with the Calls command on the Debug Menu.

Dialog Box Options

Expression

Enter the expression to be watched.  The default is the term that was selected when you chose the command.

Context

Procedure

The expression is evaluated after executing every line of code while the procedure is in the call tree.

Form/Module

The expression is evaluated after executing every line of code.

Global

The expression is evaluated after executing every line of code.

Watch Type

Watch Expression

The expression and its value appear in the upper pane of the Debug window.

Break when Expression is True

Execution automatically breaks whenever the expression evaluates to True or any nonzero value (not valid for string expressions).

Break when Expression has Changed

Execution automatically breaks whenever the value of the expression changes.


See Also

Help:

Adding, Editing and Deleting a Watch Expression

Calls Command (Debug Menu)

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Instant Watch Command (Debug Menu)

See Also

Brings up a dialog box with the current value of the selected expression.  Available only during break mode.  While debugging your program, use this command to see the current value of a variable, property, or other expression.  Select the expression and then choose the command.

Toolbar shortcut:   Keyboard shortcut: Shift+F9.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Edit Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Edit Watch Command (Debug Menu)

See Also

Brings up a dialog box in which you can edit or delete a single watch expression, delete all watch expressions, or add watch expressions.

Dialog Box Options

Options	Description

Current Expressions	Select the expression you want to change.

Edit	Brings up the Edit Watch (Add Watch) dialog with the selected expression.  The Edit Watch and Add Watch dialogs are identical.

Add	Brings up the Add Watch dialog with no expression.

Delete	Deletes the selected expression from the Current Expressions list.

Delete All	Deletes all expressions from the Current Expressions list.

Close	Closes the dialog.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Toggle Breakpoint Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Calls Command (Debug Menu)

See Also

Displays a dialog with the list of currently active procedure calls.  Available only during break mode.

When Visual Basic is executing the code in a procedure, that procedure is added to a list of active procedure calls.  If that procedure then calls another procedure, there are then two procedures on the list of active procedure calls.  Each time a procedure calls another Sub or Function, it is added to the list.  Each procedure is removed from the list as execution is returned to the calling procedure.  Procedures called from the Debug window are also added to the calls list.

Toolbar shortcut:   Keyboard shortcut: Ctrl+L.


See Also

Programmer's Guide:

Chapter 9, "Debugging"


Single Step Command (Debug Menu)

See Also

Executes one statement, advances to the next, then halts.  Use this command to run your code one line at a time when you want to see the effects of each statement.  This command is available only in break mode.

Single stepping traces through every line of Sub or Function procedures as they are invoked in your application.

If the next executable statement is outside the current module in an application that shares code, Visual Basic automatically opens the appropriate Code window.

When all statements have been executed, Visual Basic gives the focus to your application and waits for the next event.

Toolbar shortcut:   Keyboard shortcut: F8.


See Also

Help:

Executing a Specific Statement

Procedure Step Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Procedure Step Command (Debug)

See Also

This command treats Sub and Function procedures as a single executable statement as it executes one statement at a time, advances to the next executable statement, then halts.  This command is available only in break mode.

When all statements have been executed, Visual Basic gives the focus to your application and waits for the next event.

Toolbar shortcut:   Keyboard shortcut: Shift+F8.


See Also

Help:

Executing a Specific Statement

Single Step Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Toggle Breakpoint Command (Debug Menu)

See Also

Sets or removes a breakpoint at the current line.

A line of code in which a breakpoint has been set appears in the colors you specified with the Environment command on the Options menu.

This command is not available during run time.

Toolbar shortcut:   Keyboard shortcut: F9.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Edit Watch Command (Debug Menu)

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Clear All Breakpoints Command (Debug Menu)

See Also

Removes all breakpoints in your code.  When you turn off all breakpoints, your application can run in its entirety without breaking execution.

This command is not available during run time.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Edit Watch Command (Debug Menu)

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Toggle Breakpoint Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Set Next Statement Command (Debug Menu)

See Also

Changes the execution sequence of your code so that the next statement executed is the one currently selected.  Any intervening code is not executed.  Use to rerun a statement or to skip over statements you don't want to execute.  This command is available only in break mode.

You can set only the next statement within the same procedure.


See Also

Help:

Executing a Specific Statement

Programmer's Guide:

Chapter 9, "Debugging"


Show Next Statement Command (Debug Menu)

See Also

Shows the next statement to be executed when you continue running your application.

This command is available only in break mode.


See Also

Help:

Executing a Specific Statement

Programmer's Guide:

Chapter 9, "Debugging"


Environment Command (Options Menu)

See Also

Determines the attributes of the Visual Basic environment.

Dialog Box Options

Option	Description

Tab Stop Width	Width in characters.  The default is 4.

Require Variable Declaration	Determines whether Visual Basic automatically inserts an Option Explicit statement in the Declarations section of each new form and module.  The default is No.

Syntax Checking	Determines whether each line is checked for correct syntax as you enter code.  The default is Yes.

File Save Format	Determines the format for saving new forms and modules (text or binary).  You can specify an alternate format with the Save As command on the File menu.  The default is binary.

Selection Text	Color of currently selected text.

Selection Background	Background color of currently selected text.

Next Statement Text	Color of the next statement to be executed.  Identified with the Show Next Statement command from the Debug menu during break mode.

Next Statement Background	Background color of the next statement to be executed.

Breakpoint Text	Color of any breakpoint statement.

Breakpoint Background	Background color of breakpoints.

Comment Text	Color of text preceded by Rem or an apostrophe ( ' ).

Comment Background	Background color of comment text.

Keyword Text	Color of text for all reserved words and keywords.

Identifier Text	Color of text of variables, properties, and object names.

Identifier Background	Background color of variables, properties, and object names.

Code window Text	Color of values, operators, and other text.

Code window Background	Background color of values, operators, and other text.

Debug window Text	Color of all text in the Debug window.

Debug window Background	Background color of all text in the Debug window.

Grid Width	Determines the number of horizontal twips between units of the grid used to place objects on a form at design time.  The default is about 120 twips.

Grid Height	Determines the number of vertical twips between units of the grid.  The default is about 120 twips.

Show Grid	Determines whether the grid is visible at design time.  The grid does not have to be visible to align controls.  The default is Yes.

Align To Grid	Determines whether objects placed on a form automatically align to the grid.  The default is Yes.

OK	Accepts the option settings and dismisses the dialog.

Cancel	Dismisses the dialog without saving any changes to the option settings.

Reset	Resets the current option to its default value.

Reset All	Resets all options to their default values.


See Also

Help:

Setting Options

Programmer's Guide:

Chapter 1, "Introduction"


Project Command (Options Menu)

See Also

Determines option settings for the current project.

Dialog Box Options

Option	Description

Command Line Argument	Use this option to test the command line arguments you want to make available to users.  This is the text that would appear after the name of the executable file in the Command Line field of the Program Item Properties dialog in the Program Manager.

Start Up Form	The first form that is loaded when you run your application.  You can choose to specify Sub Main instead of a form.

Help File	The name of the Help file for your application.  Building a Help file requires the Microsoft Windows Help Compiler, which is available with the Visual Basic Professional Developer's Edition.  The HelpContextID property of forms and controls refers to specific topics in this file.


See Also

Help:

Setting Options

Programmer's Guide:

Chapter 1, "Introduction"


Window Menu Commands

See Also

Color Palette

Opens or activates the Color palette.

Debug

Opens or activates the Debug window.

Keyboard shortcut: Ctrl+B.

Menu Design

Opens or activates the Menu Design window.

Toolbar shortcut:   Keyboard shortcut: Ctrl+M.

Procedures

Opens the Procedures dialog box where you can select a procedure to view or edit.

Keyboard shortcut: F2.

Options	Description

Modules	Lists the modules in the current project.

Procedures	Lists the procedures in the selected module.

OK	Displays the selected procedure in the code window.

Cancel	Closes the dialog box.

Project

Opens or activates the Project window.

Properties

Opens or activates the Properties window.

Toolbar shortcut:   Keyboard shortcut: F4.

Toolbox

Opens or activates the Toolbox.


See Also

Programmer's Guide:

Chapter 1, "Introduction"


Help Menu Commands

See Also

Contents

Runs Help and displays the Visual Basic Table of Contents.

Search

Displays Help's Search dialog so you can quickly find the information you need.

Product Support

Runs Help and displays information about Microsoft Product Support services.

Introducing Microsoft Visual Basic

Runs a quick demonstration of Visual Basic features.

Learning Microsoft Visual Basic

Runs quick lessons on using Visual Basic.

About Microsoft Visual Basic

Displays a dialog box with the version number, a copyright notice, and the amount of available memory.


See Also

Help:

Introducing and Learning Visual Basic

Programmer's Guide:

Chapter 1, "Introduction"


Pattern Matching and Regular Expressions

See Also

The pattern matching used in the Find and Replace commands on the Code menu is implemented using regular expressions.  A "regular expression" is a set of characters that describes how to match a text string being searched for.  In its simplest form, a regular expression is a character-for-character match of the string you are trying to find.  Visual Basic allows you to use special characters (often called "metacharacters") to make your text searches more versatile.  In Visual Basic, regular expressions work much like the wildcard characters "*" and "?" that the operating system recognizes, but with a few enhancements.

The special characters and the way they are used is described below:

Expression	Description

*	Character wildcard.  Matches zero or more characters.  Must be enclosed in [ ] to match itself.  For example, a*a matches aa, a3a, aBa, and aBBBa.

?	Character wildcard.  Matches any one character.  Must be enclosed in [ ] to match itself.  For example, a?a matches aaa, a3a, and aBA, but not aBBBa.

#	Numeric wildcard.  Matches any one character from 0 through 9.  Must be enclosed in [ ] to match itself.  For example, a#a matches a0a, a1a, a2a, but not aaa or a10a.

[class ]	Character class.  Matches any one character in the class.  Ranges can be specified by separating starting and ending characters with a hyphen.  For example, [a-z,0-9] matches any alphanumeric character.  Because the pattern matching is not case sensitive, a-z works for both lowercase and  uppercase letters.

A class can contain multiple clauses, each separated by a comma.  Each clause can consist of a single character or a range of characters.  For example, [D-Z,0-9] matches any letters and numbers but A, B, and C.

[~class]	Not character class.  Matches any character not specified in the class.  For example [~a-z] matches anything but letters; [~0-9] matches anything but numbers.  The tilde (~) can only be used in the first character position of a class specification.  Other rules are the same as those in the character class.


See Also

Help:

Find, Find Next, Find Previous Commands (Edit Menu)


Load Picture, Load Icon Dialog Box Options

SeeAlso

Loads an existing picture or icon file.

Dialog Box Options

Option	Description

File Name	Type or select a file name from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

Drives	Select a drive from the list.

List Files of Type	Select a file type from the list:

All Picture Files (*.BMP, *.DIB, *.WMF, *.ICO) [image] lists all picture files.

Bitmaps(*.BMP, *.DIB) [image] lists bitmaps and DIBs.

Metafiles (*.WMF) [image] lists Microsoft Windows Metafiles.

All Files (*.*) [image] lists files of all types.

OK	Loads the selected file.

Cancel	Closes the dialog box without loading a picture file.


See Also

Help:

Icon Library

Icon Property

Picture Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Appendix B, "Icon Library"


Code Window

See Also

Use the Code window to write, display and edit code.  You can open as many Code windows as you want, so you can easily view the code in different forms and modules and copy and paste between them.

To open a Code window from the Project window, select a form or module name and choose the View Code button.  Choose the View Form button to see the form.

To open a Code window from a Form window, double-click a control or the form itself, or choose Code (F7) from the View menu.

The Code window includes:

The Object box.  For forms, the Object box lists the current form and all the controls on the current form.

The Procedure box.  If you are editing form code, the Procedure box lists all the events recognized by Visual Basic for the form or control displayed in the Object box.  When you select an event, either the event procedure associated with that event name, or a code template for the event, is displayed in the bottom part of the Code window.

If (general) is displayed in the Object box, the Procedure box lists all of the general procedures that have been created for the form.  If you are editing module code, the Procedure box lists all of the general procedures in the module.  In either case, the procedure you select in the Procedure box is displayed in the bottom part of the Code window.

The Split bar.  The Split bar is located across the window, below the title bar at the top of the vertical scroll bar.  Dragging this bar down splits the Code window into two horizontal panes, each of which scrolls separately.  You can then view different parts of your code at the same time.  The information that appears in the Object box and Procedure box applies to the code in the pane that has the focus.  Dragging the bar to the top of the window closes a pane.

Note	If you need help on syntax for functions, statements, properties, events, or methods while working in the Code window, type the keyword or the property, event, or method name, and press F1.  You can also select an event in the Procedure box and press F1 for information about the selected event.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Entering Declarations in Code

Guidelines for Entering and Editing Code

Learning Visual Basic:

How Visual Basic Works

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Color Palette

See Also

Use the Color palette to change the colors of a form or control and set up a custom color scheme.

To open the Color palette, choose Color Palette from the Window menu.

To close the Color palette, double-click the Color palette's Control menu.

The Color palette consists of:

A box that displays the currently selected foreground and background colors for the form or control.

A box that displays the currently selected foreground and background colors for any text in the form or control.

Note	If Microsoft Windows doesn't display the text and background colors that you've selected, it may be because one of the colors you've selected is dithered (a color comprised of up to three different colored pixels).  When displaying text in Microsoft Windows, the text and the area immediately behind it must be solid colors.  If you choose a dithered color for either the text or the background color, the nearest solid color will be used.

A set of colors.  To select a color, click the color box you want.

To change the foreground color, click the inner box on the default color box, then click the color you want.

To change the background color, click the outer box on the default color box, then click the color you want.

Click this button to use the colors specified in the Control Panel.

Click this button to display or set custom colors.

A set of custom colors.  To select a color, click the color box you want.

Click this button to open the Define Color dialog box and define custom colors.

Note	You can also set the colors for forms and controls with the ForeColor or BackColor property.


See Also

Help:

Creating Custom Colors

Setting Colors with the Color Palette

Learning Visual Basic:

Using Color and Graphics

Programmer's Guide

Chapter 2, "Your First Visual Basic Application"


Form Window

See Also

Use a Form window to create the windows and dialog boxes in your application.  You draw and view controls in a Form window.

To open a new Form window, choose New Form from the File menu or use the toolbar shortcut:

To open an existing form from the Project window, select the form name and click the View Form button.  Click the View Code button to see the code.

To add a form from another project to the current project, choose the Add File command from the File menu.

While you are designing a form:

The Form window has a Control-menu box, Minimize and Maximize buttons, and a title bar.  You can move and resize a Form window.  The form you design will have the same features at run time and in an executable file unless you specify otherwise in the form's properties.

Use the tools in the Toolbox to draw, size, and position controls.


See Also

Help

Attaching an Event Procedure to a Form or Control

Changing Grid Spacing

Setting Form and Control Properties

Learning Visual Basic:

How Visual Basic Works

Creating an Application

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Debug Window

See Also

Use the Debug window to debug your code.  This window is automatically opened at run time.  In break mode, you can use the Debug window to execute individual lines of code and to test your code.  At run time, although you can't enter statements into the Debug window, you can use it to print internal values without printing them to the actual forms.  You can also use the Debug window to monitor the value of expressions you have selected as watch expressions.

To open the Debug window, choose Debug from the Window menu.

To close the Debug window, double-click the window's Control menu.

The Debug window consists of:

The Watch pane.  Located directly beneath the Debug window title bar, this pane is visible only if you have selected a watch expression to be monitored during code execution.  The displayed information includes the context of the watch expression, the expression itself and its value at the time of the transition to break mode.  If the context of the expression is not in scope when going to break mode, the current value is not displayed.

The Immediate pane.  Located below the title bar or below the Watch pane if it is displayed, the Immediate pane is where you enter code to execute it immediately.  While working in the Immediate pane:

You can execute only one line of code at a time.

You can type or paste a line of code and press Enter to run it.

You cannot save code, but you can copy and paste it into the Code window.

In break mode, a statement in the Debug window is executed in the context displayed in the Debug window title bar.  For example, if you type Print variablename your output is the value of a local variable.  This is the same as if the Print method had actually occurred in the procedure you were executing when the program halted.


See Also

Help:

Using the Debug Window

Learning Visual Basic:

Debugging Your Application

Programmer's Guide:

Chapter 9, "Debugging"


Menu Design Window

See Also

Use the Menu Design window to create custom menus for your application and to define their properties.

To open the Menu Design window, select a form and then choose Menu Design from the Window menu.

The Menu Design window consists of:

A text box in which you enter the menu or command name that will appear on your menu bar or in your menu.

To create a separator bar in your menu, type a single hyphen (-) here.

To give the user keyboard access to the menu item, insert an ampersand (&) before a letter.  At run time, this letter is underlined, and the user can access the menu or command by pressing Alt and the letter.  If you need an ampersand in the menu, put two consecutive ampersands in the caption.

A text box in which you enter a control name for the menu item.  A control name is an identifier used only to access the menu item in code; it does not appear in a menu.

A text box in which you assign a numeric value that will determine the control's position within a control array.  This position is not related to the screen position.

A drop-down list box from which you can select a shortcut key.

A check box you select if you want the menu control to contain a list of open MDI child forms in an MDI application.

A text box where you assign the unique numeric value for the context ID.  This value is used to find the appropriate Help topic in the Help file identified by the HelpFile property.

A check box you select if you want a check mark to appear initially at the left of a menu item.  This is generally used to indicate whether a toggle option is turned on or off.

A check box you select if you want the menu item to respond to events or to be unavailable and appear dimmed.

A check box where you indicate whether you want the menu item to appear on the menu.

A set of outlining keys that enable you to move menu items to a higher or lower level:

  Use these keys to change the level of a menu from a higher level to a lower level.  You can create up to four levels of submenus.

  Use these keys to change the position of a menu item within the same menu level (up or down in the menu list).

A list box that displays a hierarchical list of menu items.  Submenu items are indented to indicate their hierarchical position or level.

The Menu Design window also has the following buttons:

Button	Description

Next	Moves selection to the next line.

Insert	Inserts a line in the list box before the currently selected line.

Delete	Deletes the currently selected line.

OK	Closes the Menu Design window and applies all menu changes to the last form you selected.  The menu is available at design time but no events are generated.

Cancel	Closes the Menu Design window and cancels all changes.


See Also

Help:

Creating a Menu Bar

Learning Visual Basic:

Adding Menus

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Project Window

See Also

The Project window displays a list of all the forms, modules, and custom controls in an application.

To open a new project, choose New Project from the File menu.

To open an existing project, choose Open Project from the File menu or use the toolbar shortcut:

While working in the Project window:

You can open the Form window for an existing form by selecting the form name and clicking the View Form button.

You can open the Code window for an existing form or module by selecting a form or module name and clicking the View Code button.

You can open as many forms and modules within a project as you want, but you can open only one Project window at a time.


See Also

Learning Visual Basic:

How Visual Basic Works

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Toolbox

See Also

The Toolbox displays all the standard Visual Basic controls plus any custom controls you have added to your project.  You choose a tool by clicking it.

To open the Toolbox, choose Toolbox from the Window menu.

To close the Toolbox, double-click the Toolbox's Control menu.

There are 21 basic tools in the Toolbox:

 Pointer.  This is the only item in the Toolbox that doesn't draw a control.  Use it to resize or move a control after it's been drawn on a form.

 Picture Box  Use to display graphical images (either decorative or active), as a container that receives output from graphics methods, or as a container for other controls.

 Label  Use for text that you don't want the user to change, such as a caption under a graphic.

 Text Box  Use to hold text that the user can either enter or change.

 Frame  Use to create a graphical or functional grouping for controls.  To group controls, draw the frame first, then draw controls inside the frame.

 Command Button  Use to create a button the user can choose to carry out a command.

 Check Box  Use to create a box that the user can easily choose to indicate if something is true or false, or to display multiple choices when the user can choose more than one.

 Option Button  Use in a group of option buttons to display multiple choices from which the user can choose only one.

 Combo Box  Use to draw a combination list box and text box.  The user can either choose an item from the list or enter a value in the text box.

 List Box  Use to display a list of items from which the user can choose one.  The list can be scrolled if it has more items than can be displayed at one time.

 Horizontal Scroll Bar  Use to provide a graphical tool for quickly navigating through a long list of items or a large amount of information, for indicating the current position on a scale, or as an input device or indicator of speed or quantity.

 Vertical Scroll Bar  Use to provide a graphical tool for quickly navigating through a long list of items or a large amount of information, for indicating the current position on a scale, or as an input device or indicator of speed or quantity.

 Timer  Use to trap timer events at set intervals.  This control is invisible at run time.

 Drive List Box  Use to display the valid drives in a selected drive.

 Directory List Box  Use to display a hierarchical list of directories in the user's system.

 File List Box  Use to display a list of files that the user can open, save, or otherwise manipulate.

 Shape  Use to draw a variety of shapes on your form at design time.  You can choose a rectangle, rounded rectrangle, square, rounded square, oval, or circle.

 Line  Use to draw a variety of line styles on your form at design time.

 Image  Use to display a graphical image from a bitmap, icon, or metafile on your form.  Images displayed in an image control can only be decorative and use fewer resources than a picture box.

 Grid  Use to create a spreadsheet-like grid consisting of columns and rows of data.

 OLE Client  Use to provide object linking and embedding (OLE) from an OLE server into your Visual Basic application.

When you select the pointer, you will be able only to resize or move a control.

When you select any other tool, you can use it only to draw new controls.

Once you draw a control, the pointer is automatically reselected.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Controls

Drawing a Control

Setting Form and Control Properties

Learning Visual Basic:

How Visual Basic Works

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Properties Window

See Also

The Properties window contains the list of properties for a selected form or control.  These properties can be changed at design time and the Properties window shows each property's current setting.  When you select multiple controls, the Properties window contains a list of the properties common to all the selected controls.

To open the Properties window, choose Properties from the Window menu or press F4.

To close the Properties window, double-click the Property window's Control menu box.

To return to the previous window, press Alt+F6.

The Properties window consists of:

The Object box.  Located beneath the title bar, the Object box identifies the currently selected form or the currently selected control on the form.  Click the arrow at the right side of the Object box to see a list that includes the current form and all the controls on the form.  From the list, choose the current form or a control on the form whose properties you want to change.

The Settings box.  Located beneath the Object box, the Settings box is where you make a change to the selected property.  If the arrow at the right side of the Settings box is dimmed, enter the property value directly by typing it in the Settings box.  If the arrow is not dimmed, click it and choose from the list of predefined settings for the property you have selected.  Click the Enter button to accept the change, or click the Cancel button to cancel the change.

The Property list.  Located at the bottom of the Properties window, this two-column list shows all properties that can be changed at design time and their current settings.  For properties that have predefined settings, double-clicking on the property name in the Property list cycles through the available choices.  For properties with only two choices, double-clicking toggles between the two choices.


See Also

Help:

Setting Colors

Setting Form and Control Properties

Learning Visual Basic:

Working with Forms and Controls

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Menu Bar and Toolbar

Click on the Menu or Toolbar word or picture for more information.

The Visual Basic menu bar includes a title bar, a Minimize button, a Maximize button, a Control menu, and the names of the menus you can use in the active window.  Although the menu bar is initially displayed at the top of the screen, it can be moved to another location and resized.

To open a menu and display its commands, click the menu name or press the access key.

To choose a command once you've opened a menu, click the command name or press the access key.  If there is a shortcut key for a command, it is indicated on the menu next to the command name.

Commands followed by an ellipsis (...) display a dialog box where you provide more information before the command is executed.

Closing the menu bar also closes Visual Basic.

The toolbar contains buttons that are shortcuts to some commonly used menu items and two indicators at the right that display the position and size of a selected form or control.


See Also

Help:

Commands


Microsoft Product Support Services

Microsoft offers a variety of support options to help you get the most from Visual Basic.

Services Within the United States

Worldwide Services

KnowledgeBase Articles on Visual Basic


See Also

Help:

Services Within the United States

Worldwide Services

KnowledgeBase Articles on Visual Basic


Microsoft Product Support Services Within the United States

See Also

Call Microsoft Fast Tips

Use the Microsoft Forum on CompuServe

Call Microsoft Product Support Services

Call Microsoft Product Support Services for the Hearing-Impaired

Use Microsoft Fee-Based Support Options

Telephoning Microsoft Product Support Services


Call Microsoft FastTips

See Also

You can hear recorded responses to common questions about Microsoft Visual Basic. You can also order technical notes that will be sent to your fax machine, and you can leave voice-mail comments or suggestions regarding Visual Basic. FastTips is available 7 days/week, 24 hours/day.

For assistance with Microsoft Visual Basic, dial (206) 646 - 5107.

You can use the following keys on your touch-tone telephone after you reach FastTips:

To advance to the next message, press *.

To repeat the current message, press 7.

To return to the beginning of FastTips, press #.


Use the Microsoft Forum on CompuServe

See Also

Microsoft Product Support Services also has access to the complete Microsoft KnowledgeBase containing answers to common questions, and descriptions of known problems are available on the Visual Basic CompuServe forum. If you are already a CompuServe member, type GO MSBASIC at any ! prompt. For an introductory CompuServe membership kit specifically for Microsoft users, dial (800) 848 - 8199 and ask for operator 230.


Call Microsoft Product Support Services

See Also

You can reach Microsoft Product Support Services between 6:00 A.M. and 6:00 P.M. Pacific time, Monday through Friday.

For setup and installation assistance with Microsoft Visual Basic, dial (206) 646 - 5105. This service is designed to get you up and running quickly with Visual Basic.

For how-to assistance and in-depth support for advanced programming issues, call Microsoft OnCall for Visual Basic at (900) 896 - 9876. The rate is $2 per minute. You can also obtain support by calling our credit card line for Visual Basic at the rate of $20 per call. To use this service, call (206) 646 - 5106. Please have your Visa, MasterCard, or American Express card ready.

When you call, you should be at your computer and have the appropriate product documentation at hand. Be prepared to give the following information:

The product version number.

The type of hardware you are using.

The exact wording of any messages that appear on your screen.

What happened and what you were doing when the problem occurred.

How you tried to solve the problem.


Call Microsoft Product Support Services for the Hearing-Impaired

See Also

You can contact Microsoft Product Support Services with a Text Telephone for the Deaf and Hearing-Impaired (TTD) by dialing (206) 635 - 4948. Call between 6:00 A.M. and 6:00 P.M. Pacific time, Monday through Friday.


Use Microsoft Fee-Based Support Options

See Also

Microsoft offers a number of other comprehensive fee-based technical support options for Visual Basic users. For more information, call (800) 227 - 4679.

Note	Microsoft support services are subject to Microsoft prices, terms, and conditions in place at the time the service is used.


Microsoft Product Support Services Worldwide

See Also

If you are outside the United States and have a question about Microsoft Visual Basic, Microsoft offers a variety of no-charge and fee-based support options. To solve your problem, you can:

1.	Consult the manuals index and other printed product documentation.

2.	Check context-sensitive online Help from the menu.

3.	Check the README files that come with your product disks.

4.	Consult electronic options, such as CompuServe forums or Bulletin Boards if available in your country.

If you cannot find a solution, you can receive information on how to obtain product support by contacting the Microsoft subsidiary office that serves your country.

Microsofts support services are subject to Microsofts prices, terms, and conditions in place in each country at the time the service is used.

Telephoning Microsoft Product Support Services

Microsoft Subsidiary Offices


Telephoning Microsoft Product Support Services

See Also

When you call, you should be at your computer with Microsoft Visual Basic running and the product documentation at hand. Have your file open and be prepared to give the following information:

The version of Microsoft Visual Basic that you are using.

The type of hardware you are using, including network hardware, if applicable.

The operating environment that you are using.

The exact wording of any messages that appeared on your screen.

A description of what happened and what you were trying to do when the problem occurred.

How you tried to solve the problem.


Microsoft Subsidiary Offices

Select a country for more information.

Argentina	Finland	Norway

Australia	France	Papua New Guinea

Austria	French Polynesia	Paraguay

Baltic States	Germany	Peru

Belgium	Hong Kong	Portugal

Bermuda	Ireland	Puerto Rico

Bolivia	Israel	Republic of China

Brazil	Italy	Republic of Ireland

Canada	Japan	Scotland

Caribbean Countries	Korea	Spain

Central America	Liechtenstein	Sweden

Chile	Luxemburg	Switzerland

Colombia	México	Uruguay

Denmark	Netherlands	Venezuela

Ecuador	New Zealand	Wales

England 	Northern Ireland


Argentina, Bolivia, Chile, Paraguay, Uruguay

Microsoft de Argentina S.A.
Phone:  (54) (1) 814 - 0356
Fax:  (54) (1) 814 - 0372


Australia, Papua New Guinea

Microsoft Pty. Ltd.
Phone:  (61) (02) 870 - 2200
Fax:  (02) 805 - 1108
BBS:  (612) 870 - 2348
Technical Support:  (61) (02) 870 - 2131
Sales Information Centre:  (02) 870 - 2100


Austria

Microsoft Ges.m.b.H.
Phone:  0222 - 68 76 07
Fax:  0222  68 16 2710
Information:  060 - 89 - 247 11 101
Prices, Updates, etc.:  060 - 89 - 3176 1199
CompuServe: msce (Microsoft Central Europe)
Technical Support:
Windows, Windows for WorkGroups, Microsoft Mail:
0660 - 65 - 10
Excel for Windows, Excel for OS/2, PowerPoint for Windows:  0660 - 65 - 11
Word for MS-DOS, Windows Write:  0660 -65 - 12
Word for Windows, Word for OS/2:  0660 - 65 - 13
Works for MS-DOS, Works for Windows, Publisher, WorksCalc, WorksText:  0660 - 65 - 14
C PDS, Fortran PDS, Pascal, Macro Assembler PDS, QuickC, QuickC for Windows, QuickPascal, QuickAssembler, Profiler:  0660 - 65 - 15
Cobol PDS, Basic PDS, QuickBasic, Visual Basic:
0660 - 65 - 16
MS-DOS:  0660 - 65 - 17
Macintosh Software:  0660 - 65 - 18
Project for Windows, Project for MS-DOS, Multiplan, Mouse, Flight Simulator, Paintbrush, Chart :  0660 - 67 - 38
FoxPro, Access:  0660 - 67 - 61


Belgium

Microsoft NV
Phone:  02 - 7322590
Fax:  02 - 7351609
Technical Support Bulletin Board Service:  02 - 7350045
(1200/2400/9600 baud, 8 bits, no parity, 1 stop bit, ANSI terminal emulation)
(Dutch-speaking) Technical Support:  02 - 5133274
(English-speaking) Technical Support:  02 - 5023432
(French-speaking) Technical Support:  02 - 5132268
Technical Support Fax:  (31) 2503 - 24304


Brazil

Microsoft Informatica Ltda.
Phone:  (55) (11) 530 - 4455
Fax:  (55) (11) 240 - 2205
Technical Support Phone:  (55) (11) 533 - 2922
Technical Support Fax:  (55) (11) 241 - 1157
Technical Support BBS:  (55) (11) 543 - 9257
Developers Link Membership Information : (55) (11) 530 4455


Canada

Microsoft Canada Inc.
Phone:  1 (416) 568 - 0434
Fax:  1 (416) 568 - 4689
Technical Support Phone:  1 (416) 568 - 3503
Technical Support Fax:  1 (416) 568 - 4689
Technical Support BBS:  1 (416) 507 - 3022


Denmark

Microsoft Danmark AS
Phone:  (45) (44) 89 01 00
Fax:  (45) (44) 68 55 10


England, Ireland, Northern Ireland, Scotland

Microsoft Limited
Phone:  (44) (734) 270000
Fax:  (44) (734) 270002
Upgrades:  (44) (81) 893  -  8000
Technical Support:
Main Line (All Products):  (44) (734) 271000
Windows Direct Support Line:  (44) (734) 271001
Database Direct Support Line:  (44) (734) 271126
MS-DOS 5 Warranty Support:  (44) (734) 271900
MS-DOS 5 Fee Support Line:  (44) (891) 315500
OnLine Service Assistance:  (44) (734) 270374
Bulletin Board Service:  (44) (734) 270065 (2400 baud)
Fax Information Service:  (44) (734) 270080


Finland

Microsoft OY
Phone:  (358) (0) 525 501
Fax:  (358) (0) 522 955


France, French Polynesia

Microsoft France
Phone:  (33) (1) 69 - 86 - 46 - 46
Telex:  MSPARIS 604322F
Fax:  (33) (1) 64 - 46 - 06 - 60
Technical Support Phone:  (33) (1) 69 - 86 - 10 - 20
Technical Support Fax:  (33) (1) 69 - 28 - 00 - 28


Germany, Baltic States

Microsoft GmbH
Phone:  089 - 3176 - 0
Telex:  (17) 89 83 28 MS GMBH D
Fax:  089 - 3176 - 1000
Information:  0130 - 5099
Prices, Updates, etc.:  089 - 3176 - 1199
Bulletin Board, Device Drivers, Tech Notes:
BTX: microsoft# or *610808000#
CompuServe:  msce (Microsoft Central Europe)
Technical Support:
Windows, Windows for WorkGroups, Microsoft Mail:
089 - 3176 - 1110
Excel for Windows, Excel for OS/2, PowerPoint for Windows:  089 - 3176 - 1120
Word for MS-DOS, Windows Write:  089 - 3176 - 1130
Word for Windows, Word for OS/2:  089 - 3176 - 1131
Works for MS-DOS, Works for Windows, Publisher, WorksCalc, WorksText:  089 - 3176 - 1140
C PDS, Fortran PDS, Pascal, Macro Assembler PDS, QuickC, QuickC for Windows, QuickPascal, QuickAssembler, Profiler:  089 - 3176 - 1150
Cobol PDS, Basic PDS, QuickBasic, Visual Basic:
089 - 3176 - 1151
MS-DOS:  089 - 3176 - 1152
Macintosh Software:  089 - 3176 - 1160
Project for Windows, Project for MS-DOS, Multiplan, Mouse, Flight Simulator, Paintbrush, Chart:
089 - 3176 - 1170
FoxPro, Access:  089 - 3176 - 1180


Hong Kong

Microsoft Hong Kong Limited
Technical Support:  (852) 804 - 4222


Israel

Microsoft Israel Ltd.
Phone:  972 - 3 - 752 - 7915
Fax:  972 - 3 - 752 - 7919


Italy

Microsoft SpA
Phone:  (39) (2) 269121
Telex:  340321 I
Fax:  (39) (2) 21072020
Technical Support:
Excel, Project, WinWorks:  (39) (2) 26901361
Word, PC Works:  (39) (2) 26901362
Windows, PowerPoint, Publisher, Windows for WorkGroups, MAC Works:  (39) (2) 26901363
Basic, Cobol, Visual Basic, MS-DOS, Access, FoxPro:
  (39) (2) 26901364
C, Fortran, Pascal, MASM and SDKs:  (39) (2) 26901354
LAN Manager, SQL Server, Mail, Mail Gateways:
(39) (2) 26901356


Japan

Microsoft Company Ltd.
Phone:  (81) (3) 3363 - 1200
Fax:  (81) (3) 3363 - 1281
Technical Support:
MS-DOS Applications:  (81) (3) 3363 - 0160
Windows Applications:  (81) (3) 3363 - 5040
Language Products (Microsoft C, MASM, QuickC):
(81) (3) 3363 - 7610
Language Products (Basic, FORTRAN, Visual Basic, QuickBasic):  (81) (3) 3363 - 0170
All Products Technical Support Fax:  (81) (3) 3363 - 9901


Korea

Microsoft CH
Phone:  (82) (2) 552 - 9505
Fax:  (82) (2) 555 - 1724
Technical Support:  (82) (2) 563 - 9230


Luxemburg

Microsoft NV
Phone:  (32) 2 - 7322590
Fax:  (32) 2 - 7351609
Technical Support Bulletin Board Service:
(31) 2503 - 34221 (1200/2400/9600 baud, 8 bits, no parity, 1 stop bit, ANSI terminal emulation)
(Dutch-speaking) Technical Support:  (31) 2503 - 77877
(English-speaking) Technical Support:  (31) 2503 - 77853
(French-speaking) Technical Support:  (32) 2 - 5132268
Technical Support Fax:  (31) 2503 - 24304


México

Microsoft México, S.A. de C.V.
Phone:  (52) (5) 325 - 0910
Fax:  (52) (5) 280 - 0198
Technical Support:  (52) (5) 325 - 0912
Sales:  (52) (5) 325 - 0911


Netherlands

Microsoft BV
Phone:  02503 - 13181
Fax:  02503 - 37761
Technical Support Bulletin Board Service:  02503 - 34221 (1200/2400/9600 baud, 8 bits, no parity, 1 stop bit, ANSI terminal emulation)
(Dutch-speaking) Technical Support:  02503 - 77877
(English-speaking) Technical Support:  02503 - 77853
Technical Support Fax:  02503 - 24304


New Zealand

Technology Link Centre
Phone:  64 (9) 358 - 3724
Fax:  64 (9) 358 - 3726
Technical Support Applications:  64 (9) 357 - 5575


Norway

Microsoft Norway AS
Phone:  (47) (2) 95 06 65
Fax:  (47) (2) 95 06 64
Technical Support:  (47) (2) 18 35 00


Portugal

MSFT, Lda.
Phone:  (351) 1 4412205
Fax:  (351) 1 4412101


Republic of China

Microsoft Taiwan Corp.
Phone:  (886) (2) 504 - 3122
Fax:  (886) (2) 504 - 3121


Spain

Microsoft Iberica SRL
Phone:  (34) (1) 804 - 0000
Fax:  (34) (1) 803 - 8310
Technical Support:  (34) (1) 803 - 9960


Sweden

Microsoft AB
Phone:  (46) (8) 752 56 00
Fax:  (46) (8) 750 51 58
Technical Support:
Applications:  (46) (8) 752 68 50
Development & Network Products:  (46) (8) 752 60 50
MS-DOS:  (46) (071) 21 05 15 (SEK 4.55/min)
Sales Support:  (46) (8) 752 56 30
Bulletin Board Service:  (46) (8) 750 47 42
Fax Information Service:  (46) (8) 752 29 00


Leichtenstein, Switzerland

(German-speaking)
Microsoft AG
Phone:  01 - 839 61 11
Fax:  01 - 831 08 69
Information:  0049 - 89 - 247 11 101
Prices, Updates, etc.:  0049 - 89 - 3176 1199
CompuServe:  msce (Microsoft Central Europe)
Technical Support:
Windows, Windows for WorkGroups, Microsoft Mail:
01 - 342 - 4085
Excel for Windows, Excel for OS/2, PowerPoint for Windows:  01 - 342 - 4082
Word for MS-DOS, Windows Write:  01 - 342 - 4083
Word for Windows, Word for OS/2:  01 - 342 - 4087
Works for MS-DOS, Works for Windows, Publisher, WorksCalc, WorksText:  01 - 342 - 4084
C PDS, Fortran PDS, Pascal, Macro Assembler PDS, QuickC, QuickC for Windows, QuickPascal, QuickAssembler, Profiler:  01 - 342 - 4036
Cobol PDS, Basic PDS, QuickBasic, Visual Basic:
01 - 342 - 4086
MS-DOS:  01 - 342 - 2152
Macintosh Software:  01 - 342 - 4081
Project for Windows, Project for MS-DOS, Multiplan, Mouse, Flight Simulator, Paintbrush, Chart :  01 - 342 - 0322
FoxPro, Access:  01 -342 - 4121
(French-speaking)
Microsoft SA, office Nyon
Phone:  022 - 63 68 11
Fax:  022 - 363 69 11
Technical Support:  022 - 738 96 88


Bermuda, Caribbean Countries, Central America,
Colombia, Ecuador, Peru, Puerto Rico, Venezuela

Corporation MS 90 de Venezuela S.A.
Phone:  0058.2.914739
Fax:  0058.2.923835


LinkItem Property

See Also	Example

Applies To

Label, picture box, text box.

Description

Specifies the data passed to a destination control in a DDE conversation with another application; corresponds to the item argument in the standard DDE syntax, with application, topic, and item as arguments.

Usage

[form.]{label|picturebox|textbox}.LinkItem[ = stringexpression ]

Remarks

To set this property, specify a recognizable unit of data in an application as a reference [image] for example, a cell reference such as "R1C1" in Microsoft Excel.

Use LinkItem in combination with the LinkTopic property to specify the complete data link for a destination control to a source application.  To activate this link, set the LinkMode property.

You set LinkItem only for a control used as a destination.  When a Visual Basic form is a source in a DDE conversation, the name of any label, picture box, or text box on the form can be the item argument in the application|topic!item string used by the destination.  For example, the syntax:  =VizBasicApplication|MyForm!TextBox1 represents a valid reference from Microsoft Excel to a Visual Basic application.  You would enter this syntax for a destination cell in Microsoft Excel's formula bar.

Avoiding infinite loops  A DDE control can potentially act as destination and source simultaneously, causing an infinite loop if a destination-source pair is also a source-destination pair with itself.  For instance, a text box may be both a source (through its parent form) and destination of the same cell in Microsoft Excel.  When data in a Visual Basic text box changes, sending data to Microsoft Excel, the cell in Microsoft Excel changes, sending the change to the text box, and so on, causing the loop.

To avoid such loops, use related but not identical items for destination-source and source-destination links in both directions between applications.  For example, in Microsoft Excel, use related cells (precedents or dependents) to link a worksheet with a Visual Basic control, thus avoiding using a single item as both destination and source.  You should document any application|topic pairs you establish if you include a Paste Link command for run-time use.

Note	Setting a permanent data link at design time with the Paste Link command from the Edit menu also sets the LinkMode, LinkTopic, and LinkItem properties.  This creates a link that is saved with the form.  Each time the form is loaded, Visual Basic attempts to reestablish the conversation.

Data Type

String


See Also

Help:

Creating a DDE Destination or Source Link

LinkSend Method

LinkMode Property

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkMode Property

See Also	Example

Applies To

Form, label, picture box, text box.

Description

Determines the type of link used for a DDE conversation and activates the connection as follows:

Control [image] allows a destination control on a Visual Basic form to initiate a conversation as specified through the control's LinkTopic and LinkItem properties.

Form [image] allows a destination application to initiate a conversation with a Visual Basic source form, as specified through the destination application's application|topic!item expression.

Usage

[form.][label.|picturebox.|textbox.]LinkMode[ = mode ]

Remarks

For controls used as destinations in DDE conversations, the LinkMode property settings are:

Setting	Description

0	(Default) None.  No DDE interaction.

1	Automatic.  Destination control is updated each time the linked data changes.

2	Manual.  Destination control is updated only when the LinkRequest method is invoked.

3	Notify.  A LinkNotify event occurs whenever the linked data changes, but the destination control is updated only when the LinkRequest method is invoked.

For forms used as sources in DDE conversations, the LinkMode property settings are:

Setting	Description

0	(Default) None.  No DDE interaction.  No destination application can initiate a conversation with the source form as the topic, and no application can poke data to the form.  If LinkMode is 0 (None) at design time, you cannot change it to 1 (Source) at run time.

1	Source.  Allows any label, picture box, or text box on a form to supply data to any destination application that establishes a DDE conversation with the form.  If such a link exists, Visual Basic automatically notifies the destination whenever the contents of a control are changed.  In addition, a destination application can poke data to any label, picture box, or text box on the form.  If LinkMode is 1 (Source) at design time, you can change it to 0 (None) and back at run time.

The following conditions also apply to the LinkMode property:

Setting LinkMode to a nonzero value for a destination control causes Visual Basic to attempt to initiate the conversation specified in the LinkTopic and LinkItem properties.  The source updates the destination control according to the type of link specified (automatic, manual, or notify).

If a label, picture box, or text box has established an automatic link with a source application, a Change event occurs for that control each time new data is entered, whether or not the value of the data differs from the control's current contents.  Note that this is the only way a Change event can occur for a label control.

If a source application terminates a conversation with a Visual Basic destination control, the value for that controls LinkMode setting changes to 0 (None).

If you leave LinkMode for a form set to the default 0 (None) at design time, you cannot change LinkMode at run time. If you want a form to act as a source, you must set LinkMode to 1 (Source) at design time. You can then change the value of LinkMode at run time.

Note	Setting a permanent data link at design time with the Paste Link command from the Edit menu also sets the LinkMode, LinkTopic, and LinkItem properties.  This creates a link that is saved with the form.  Each time the form is loaded, Visual Basic attempts to reestablish the conversation.

Data Type

Integer


See Also

Help:

Creating a DDE Destination or Source Link

LinkClose Event

LinkError Event

LinkExecute Method

LinkItem Property

LinkNotify Event

LinkOpen Event

LinkSend Method

LinkTimeout Property

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkTimeout Property

See Also

Applies To

Label, picture box, text box.

Description

Determines the amount of time a control waits for a response to a DDE message.

Usage

[form.]{label|picturebox|textbox}.LinkTimeout[ = duration ]

Remarks

By default, the LinkTimeout property is set to 50 (equivalent to 5 seconds).  You can specify other settings in tenths of a second.

DDE response time from source applications varies.  Use this property to adjust the time a destination control waits for a response from a source application.  This helps avoid generating an error by Visual Basic if a given source application takes too long to respond.

Note	The maximum length of time that a control can wait is 65535 tenths of a second, or about 1 hour 49 minutes.  Setting LinkTimeout to -1 tells the control to wait the maximum length of time for a response in a DDE conversation.  The user can force the control to stop waiting by pressing the Esc key.

Data Type

Integer


See Also

Help:

LinkClose Event

LinkItem Property

LinkMode Property

LinkOpen Event

LinkSend Method

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkTopic Property

See Also	Example

Applies To

Form, label, picture box, text box.

Description

For a destination control [image] determines the source application and the topic.  You use LinkTopic with the LinkItem property to specify the complete data link.

For a source form [image] determines the topic that the source form responds to in a DDE conversation.

Usage

[form.][label.|picturebox.|textbox.]LinkTopic[ = link ]

Remarks

The LinkTopic property consists of a string that supplies part of the information necessary to set up either a destination link or source link.  The string you use depends on whether you're working with a destination control or a source form.  Each string corresponds to one or more elements of standard DDE syntax [image] application, topic, and item.

Destination control  To set LinkTopic for a destination control, use a string with the syntax application|topic, as follows:

application is the name of the application from which data is requested, usually the executable file name without any extension [image] for example, "Excel" (for Microsoft Excel).

The "pipe" character (|, or character code 124) separates the application from the topic.

topic is the fundamental data grouping used in that application [image] for example, a worksheet in Microsoft Excel.

In addition, for a destination control only, you need to set the related LinkItem property to specify the item element for the link.  A cell reference such as "R1C1," for example, would correspond to an item in a Microsoft Excel worksheet.

Source form  To set LinkTopic for a source, change the default string, FormN, to an appropriate identifier for the form.  A destination application uses this string as the topic argument when establishing a DDE link with the form.  Although this string is all you need to set LinkTopic within Visual Basic for a source form, the destination application itself also needs to specify:

The application element that the destination application uses, which is either the Visual Basic project name without the .MAK extension (if you are running your application in the Visual Basic development environment), or the Visual Basic application name without the .EXE extension (if you are running your application as a stand-alone executable file).  The EXEName property of the App object object provides this string in your Visual Basic code unless the file name was changed by the user.  (App.EXEName always returns the actual file name of the application on disk, whereas DDE always uses the original name that was specified in the Make EXE dialog.)

The item element that the destination application uses, which corresponds to the Name property for the label, picture box, or text box on the source form.

An example of a valid reference from Microsoft Excel to a Visual Basic application acting as a source is:  =VizBasicApplication|FormN!TextBox1.  You would enter this reference for a destination cell in Microsoft Excel's formula bar.

Strings and syntax  While the standard definition for a DDE link includes the application, topic, and item elements, the actual syntax used within applications for a destination link to a source application may vary slightly.  For example, within Microsoft Excel, you use the syntax application|topic!item.  Within Microsoft Word for Windows, you use application topic item (no pipe character or exclamation mark).  Within a Visual Basic application, you use application|topic; the exclamation mark (!) for topic is implicit.

Activating and maintaining data links  To activate the data link set with LinkTopic, set the LinkMode property to the appropriate nonzero value to specify the type of link you want.  As a general rule, you should set LinkMode after you specify LinkTopic.  For a destination control, changing LinkTopic breaks an existing link and terminates the DDE conversation.  For a source form, changing LinkTopic breaks all destination links that are using that topic.  For these reasons, you should always set the LinkMode property to 0 before changing LinkTopic.  After changing LinkTopic for a destination control, you must set LinkMode to 1 (Automatic), 2 (Manual), or 3 (Notify) to establish a conversation with the new topic.

Note	Setting a permanent data link at design time with the Paste Link command from the Edit menu also sets the LinkMode, LinkTopic, and LinkItem properties.  This creates a link that is saved with the form.  Each time the form is loaded, Visual Basic attempts to reestablish the conversation.

Data Type

String


See Also

Help:

Creating a DDE Destination or Source Link

LinkClose Event

LinkError Event

LinkItem Property

LinkMode Property

LinkOpen Event

LinkSend Method

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkItem, LInkMode, LinkTopic Properties Example

In the example, each mouse click causes a cell in a Microsoft Excel worksheet to update the contents of a Visual Basic text box.  To try this example, start Microsoft Excel, open a new worksheet named Sheet1, and put some data in the first column.  Then in Visual Basic, create a form with a text box.  Paste the code into the Declarations section and press F5 to run the program.

Sub Form_Click ()

Dim CurRow As String

Static Row	' Worksheet row number.

Row = Row + 1	' Increment Row.

If Row = 1 Then	' First time only.

' Make sure the link is not active.

Text1.LinkMode = 0

' Set the application name and topic name.

Text1.LinkTopic = "Excel|Sheet1"

Text1.LinkItem = "R1C1"	' Set the LinkItem.

Text1.LinkMode = 1	' Activate the link to 	' Automatic.

Else

' Update the Row in the data item.

CurRow = "R" & Row & "C1"

Text1.LinkItem = CurRow	' Set the LinkItem.

End If

End Sub


LinkClose Event

See Also

Applies To

Form, MDI Form, label, picture box, text box.

Description

Occurs when a DDE conversation terminates.  Either application in a DDE conversation may terminate a conversation at any time.

Syntax

Sub {Form|MDIForm}_LinkClose ( )

Sub ctlname_LinkClose (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, you use a LinkClose procedure to notify the user that a DDE conversation has been terminated.  You might also include troubleshooting information on reestablishing a connection or where to go for assistance.  For brief messages, use the MsgBox function or statement.


See Also

Help:

LinkError Event

LinkExecute Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkError Event

See Also	Example

Applies To

Form, MDI Form, label, picture box, text box.

Description

Occurs when there is an error during a DDE conversation.  This event is recognized only as the result of a DDE-related error that occurs when no Visual Basic code is being executed.  The error number is passed as an argument.

Syntax

Sub {Form|MDIForm}_LinkError (LinkErr As Integer)

Sub ctlname_LinkError ([Index As Integer,]LinkErr As Integer)

Remarks

The LinkError event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

LinkErr	The error number.

Use a LinkError procedure to notify the user of the particular error that has occurred.  You might also include code to fix the problem, or troubleshooting information on reestablishing a connection or on where to go for assistance.  For brief messages, use the MsgBox function and MsgBox statement.

The following table lists all error numbers returned for the LinkErr argument and a brief explanation of each error.

Error number	Explanation

1	The other application has requested data in the wrong format.  This error may occur several times in succession as Visual Basic tries to find a format the other application recognizes.

6	The destination application attempted to continue performing DDE after you set the LinkMode on your source form to 0 (None).

7	All the source links are in use (there is a limit of 128 links per source).

8	For destination controls: an automatic link or LinkRequest method failed to update the data in the control.

For source forms: the destination attempted to poke data to a control and the attempt failed.

11	Not enough memory for DDE.

The missing numbers in this table correspond to error values that were supported in Visual Basic 1.0 but no longer occur in Visual Basic 2.0.


See Also

Help:

LinkClose Event

LinkExecute Event

LinkExecute Method

LinkItem Property

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkError Event Example

The example is attached to a text box control, MyTextBox, which handles selected errors.  The procedure displays a message (adapted from the error list in the LinkError Event topic), based on the error number passed as the argument LinkErr.  Note that you can adapt this code to a source form by substituting Form_LinkError for MyTextBox_LinkError.  This example is for illustration only.

Sub MyTextBox_LinkError (LinkErr As Integer)

Dim Msg

Select Case LinkErr

Case 1

Msg = "Data in wrong format."

Case 11

Msg = "Out of memory for DDE."

End Select

MsgBox Msg, 48, "MyTextBox"

End Sub


LinkExecute Event

See Also	Example

Applies To

Form, MDI Form.

Description

Occurs when a command string is sent by a destination application in a DDE conversation. The destination application expects the source application to perform the operation described by the string.

Syntax

Sub {Form|MDIForm}_LinkExecute (CmdStr As String, Cancel As Integer)

Remarks

The LinkExecute event uses these arguments:

Argument	Description

CmdStr	The command string sent by the destination application.

Cancel	This argument's value at the end of the LinkExecute event procedure tells the destination whether the command string was accepted or refused.  Setting Cancel = 0 informs the destination that the command string was accepted.  Setting Cancel to any nonzero value informs the destination that the command string was rejected.  (The default is set to -1, indicating Cancel.)

There is no required syntax for CmdStr.  How your application responds to different strings is completely up to you.

If you have not created a LinkExecute event procedure, Visual Basic rejects command strings from destination applications.


See Also

Help:

Attaching an Event Procedure to a Form or Control

LinkClose Event

LinkError Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkExecute Event Example

The example defines a set of commands for destinations to use in DDE conversations to which your application will respond.  This example is for illustration only.

Sub Form_LinkExecute (CmdStr As String, Cancel As Integer)

Cancel = False

Select Case LCase(cmdStr)

Case "{big}"

WindowState = 2	' Maximize window.

Case "{little}"

WindowState = 1	' Minimize window.

Case "{hide}"

Visible = False	' Hide form.

Case "{view}"

Visible = True	' Display form.

Case Else

Cancel = True	' Execute not allowed.

End Select

End Sub


LinkNotify Event

See Also	Example

Applies To

Label, picture box, text box.

Description

Occurs when the source has changed the data defined by the DDE link, if the LinkMode property of the destination control is set to 3 (Notify).

Syntax

Sub ctlname_LinkNotify (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, in the LinkNotify event your code notifies the user, gets the new data immediately, or defers getting the data until later.  You can use the LinkRequest method to obtain the new data from the source.


See Also

Help:

Attaching an Event Procedure to a Form or Control

LinkClose Event

LinkError Event

LinkExecute Method

LinkMode Property

LinkOpen Event

LinkRequest Method

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkNotify Event Example

The example is attached to a picture box control, Picture1, which has its LinkMode property set to 3 (Notify) and its LinkTopic and LinkItem properties set to specify picture data in the source.  When the source changes this data, the procedure updates the picture box immediately only if the picture box is on the active form (the form that has the focus); otherwise it sets a flag variable.  The example is for illustration only.

Sub Picture1_LinkNotify ()

If Screen.ActiveForm Is Me Then

Picture1.LinkRequest	' Picture is on active form, so update.

Else

NewDataFlag = True	' Assumed to be a module-level variable.

End If

End Sub


LinkOpen Event

See Also

Applies To

Form, MDI Form, label, picture box, text box.

Description

Occurs when a DDE conversation is being initiated.

Syntax

Sub {Form|MDIForm}_LinkOpen (Cancel As Integer)

Sub ctlname_LinkOpen ([Index As Integer,]Cancel As Integer)

Remarks

The LinkOpen event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Cancel	When the LinkOpen event procedure ends, the value of this argument determines whether the DDE conversation is established or not.  Leaving Cancel = 0 establishes the conversation.  Setting Cancel to any nonzero value refuses the conversation.

This event occurs for forms when a destination application is initiating a DDE conversation with the form.  It occurs for controls when a control is initiating a DDE conversation with a source application.


See Also

Help:

LinkClose Event

LinkError Event

LinkExecute Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


KnowledgeBase Articles from Microsoft Product Support

DDE Example Between Visual Basic and Word For Windows

DDE From Visual Basic to Excel For Windows

Example of DDE Between Visual Basic Applications

How to Create Scrollable Viewports in Visual Basic

How to Get Windows Master List (Task List) Using Visual Basic

How to Print a VB Picture Control Using Windows API Functions

How to Use Windows BITBLT Function From Visual Basic

How VB Can Determine If a Specific Windows Program Is Running

LSTRCPY API Call to Receive LPSTR Returned From Other API s

VB Can Determine When a Shelled Process Has Terminated


HOW TO CREATE SCROLLABLE VIEWPORTS IN VISUAL BASIC
HOW TO CREATE SCROLLABLE VIEWPORTS IN VISUAL BASIC	Q71068

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

Scrollable viewports can be created within Visual Basic using standard

Basic calls. The viewports can include bitmaps, graphics, or other

controls.

This information is included with the Help file provided with

the Microsoft Professional Toolkit for Microsoft Visual Basic

programming system version 2.0 for Windows.

More Information:

To create a scrollable picture with clipping, you must have two

picture controls. The first picture control is called the stationary

parent picture control. Within the parent picture control, you need to

create a movable child picture control. It is the child picture

control that will be moved within the parent picture control. Moving

the child picture within the parent picture control creates the

clipping effect. During run time when you move the child picture, it

will now be clipped by the boundaries of the parent picture.

To create these two picture controls, do the following:

1. Choose the picture box control from the Toolbox window in Visual

   Basic.

2. Draw a picture on the form. This is the parent picture.

3. Again choose the picture box control from the Toolbox window.

4. Draw the second picture on top of and within the boundaries of

   the first picture control. This is the child picture.

The sample application below shows how to create a scrollable bitmap

within a viewport. Perform the sequence above to create a parent/child

picture control. Add a horizontal scroll bar and a vertical scroll bar

to the form.

Make sure that the path to your bitmap is correct. Several of the

properties are set during run time, which could have been set during

design time as well.

Moving the thumb of the two scroll bars will move the child picture

within the parent picture. The handle (upper-left corner of the

picture) to the child picture will be located either at (0,0) of the

parent picture or to the left and/or right of the parent picture.

Since the clipping region is that of the parent picture, the child

picture will appear to move across the parent picture viewport.

Sub Form_Load ()

   Const PIXEL = 3

   Add the following 2 constants only in Visual Basic 1.0:

   '  Const TRUE = -1

   '  Const NONE = 0

   ' Set design properties, included here for simplicity.

   Form1.ScaleMode = PIXEL

   Picture1.ScaleMode = PIXEL

   Picture2.ScaleMode = PIXEL

   ' AutoSize is set to TRUE so that the boundaries of

   ' Picture2 are expanded to the size of the actual bitmap.

   Picture2.AutoSize = TRUE

   ' Get rid of annoying borders.

   Picture1.BorderStyle = NONE

   Picture2.BorderStyle = NONE

   ' Load the picture that you want to display.

   Picture2.Picture = LoadPicture("c:\win\party.bmp")

   ' Initialize location of both pictures.

   Picture1.Move 0, 0, ScaleWidth - VScroll1.Width,_

ScaleHeight - HScroll1.Height

   Picture2.Move 0, 0

   ' Position the horizontal scroll bar.

   HScroll1.Top = Picture1.Height

   HScroll1.Left = 0

   HScroll1.Width = Picture1.Width

   ' Position the vertical scroll bar.

   VScroll1.Top = 0

   VScroll1.Left = Picture1.Width

   VScroll1.Height = Picture1.Height

   ' Set the Max value for the scroll bars.

   HScroll1.Max = Picture2.Width - Picture1.Width

   VScroll1.Max = Picture2.Height - Picture1.Height

   ' Determine if child picture will fill up screen.

   ' If so, then there is no need to use scroll bars.

   VScroll1.Enabled = (Picture1.Height < Picture2.Height)

   HScroll1.Enabled = (Picture1.Width < Picture2.Width)

End Sub

Sub HScroll1_Change ()

  ' Picture2.Left is set to the negative of the value because

  ' as you scroll the scroll bar to the right, the display

  ' should move to the Left, showing more of the right

  ' of the display, and vice-versa when scrolling to the

  ' left.

   Picture2.Left = -HScroll1.Value

End Sub

Sub VScroll1_Change ()

  ' Picture2.Top is set to the negative of the value because

  ' as you scroll the scroll bar down, the display

  ' should move up, showing more of the bottom

  ' of the display, and vice-versa when scrolling up.

   Picture2.Top = -VScroll1.Value

End Sub


HOW TO PRINT A VB PICTURE CONTROL USING WINDOWS API FUNCTIONS
HOW TO PRINT A VB PICTURE CONTROL USING WINDOWS API FUNCTIONS	Q77060

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

This article explains how to print a Visual Basic picture control to a

printer using several Windows 3.x API function calls.

Note that this example will not work correctly on PostScript printers.

Instead of the picture control printing, two blank sheets are ejected

from the printer when using a printer configured to use the PostScript

printer driver. For the example to work correctly, the printer must

use a standard non-PostScript laser printer configuration (such as

PCL/HP.)

This information is included with the Help file provided with

the Microsoft Professional Toolkit for Microsoft Visual Basic

programming system version 2.0 for Windows.

More Information:

To print a picture control from Visual Basic, you must use the

PrintForm method. Although this can very useful, there is no

straightforward method of printing just a picture control without the

use of API function calls. Printing a picture control to the printer

is useful when you want to control the location or size of the printed

image. Calling API functions to print a picture control is also useful

if you want to include other images or text along with the picture

image on a single sheet of paper.

To print a bitmap, you need to do the following:

1. Create a memory device context that is compatible with the

   bitmap (CreateCompatibleDC). A memory device context is a block of

   memory that represents a display surface. It is used to prepare

   images before copying them to the actual device surface of the

   compatible device.

2. Save the present object (SelectObject) and select the picture

   control using the handle from the memory device context.

3. Use the BitBlt or StretchBlt function to copy the bitmap from the

   memory device context to the printer.

4. Remove the bitmap from the memory device context (SelectObject) and

   delete the device context (DeleteDC).

The following steps demonstrate this process:

1. Run Visual Basic, or from the File menu, choose New Project (ALT,

   F, N) if Visual Basic is already running. Form1 is created by

   default.

2. Add a picture (Picture1) control to Form1 and set the AutoRedraw

   property to True from the Properties bar.

3. Add a command (Command1) button.

4. Display some graphics in Picture1 by loading from a picture file or

   pasting from the Clipboard at design time. You can load a picture

   from a file as follows:

   a. Select the Picture property from the Properties window.

   b. Click the arrow at the right of the Settings box, then select the

      desired picture file (such as a .BMP or .ICO file supplied with

      Microsoft Windows) from the dialog box.

5. Add the following declarations to the global Declarations section of

   the Code window. Note: Each Declare statement must be on one line:

Declare Function CreateCompatibleDC% Lib "GDI" (ByVal hDC%)

Declare Function SelectObject% Lib "GDI" (ByVal hDC%, ByVal hObject%)

Declare Function StretchBlt% Lib "GDI"	(ByVal hDC%, ByVal X%,

ByVal Y%, ByVal nWidth%,

ByVal nHght%, ByVal hSrcDC%,

ByVal XSrc%, ByVal YSrc%,

ByVal nSrcWidth%,

ByVal nSrcHeight%,

ByVal dwRop&)

Declare Function DeleteDC% Lib "GDI" (ByVal hDC%)

Declare Function Escape% Lib "GDI"	(ByVal hDC As Integer,

ByVal nEscape As Integer,

ByVal nCount As Integer,

LpInData As Any,

LpOutData As Any)

6. Add the following code to the Command_Click event:

Sub Command1_Click ()

   ' Const NULL = 0&

   Const SRCCOPY = &HCC0020

   Const NEWFRAME = 1

   Const PIXEL = 3

   '* display hour glass

   MousePointer = 11

   Picture1.Picture = Picture1.Image

   '* StretchBlt requires pixel coordinates.

   Picture1.ScaleMode = PIXEL

   Printer.ScaleMode = PIXEL

   Printer.Print " "

   hMemoryDC% = CreateCompatibleDC(Picture1.hDC)

   hOldBitMap% = SelectObject(hMemoryDC%, Picture1.Picture)

   ApiError% = StretchBlt(Printer.hDC, 0, 0,

Printer.ScaleWidth, Printer.ScaleHeight,

hMemoryDC%, 0, 0, Picture1.ScaleWidth,

Picture1.ScaleHeight, SRCCOPY)

   hOldBitMap% = SelectObject(hMemoryDC%, hOldBitMap%)

   ApiError% = DeleteDC(hMemoryDC%)

   Print Escape(Printer.hDC, NEWFRAME, 0, NULL, NULL)

   Printer.EndDoc

   MousePointer = 1

End Sub

7. Run the program to copy the bitmap to the printer. If you have

   selected a low resolution from the Print Manager, printing the

   bitmap will proceed quickly (the lower the resolution, the faster

   the print time). While designing your software, you may want

   to keep this at the lowest possible resolution. The print

   resolution can be changed from the Windows Control Panel.

Reference(s):

"Programming Windows: The Microsoft Guide to Writing Applications

for Windows 3," Charles Petzold, Microsoft Press, 1990

"Microsoft Windows Software Development Kit: Reference Volume 1,"

version 3.0

"Microsoft Windows Software Development Kit: Guide to Programming,"

version 3.0.

WINSDK.HLP file shipped with Microsoft Windows 3.0 Software

Development Kit


LSTRCPY API CALL TO RECEIVE LPSTR RETURNED FROM OTHER APIS
LSTRCPY API CALL TO RECEIVE LPSTR RETURNED FROM OTHER APIs	Q78304

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

Because Microsoft Visual Basic does not support a pointer data type,

you cannot directly receive a pointer (such as a LPSTR) as the return

value from a Windows API or DLL function. You can work around this

limitation by receiving the return value as a long integer data type

and then using the lstrcpy Windows API function to copy the returned

string into a Visual Basic string.

More Information:

An LPSTR Windows API data type is actually a far pointer to a

null-terminated string of characters. Because an LPSTR is a far

pointer, it can be received as a four byte data type, such as a Visual

Basic long integer. Using the Visual Basic "ByVal" keyword, you can

pass the address stored in a Visual Basic long integer back to the

Windows API lstrcpy routine to copy the characters at that address

into a Visual Basic string variable. Because lstrcpy expects the

target string to be long enough to hold the source string, you should

pad any Visual Basic string passed to lstrcpy to have a size large

enough to hold the source string before passing it to lstrcpy. Failure

to allocate enough space in the Visual Basic string may result in an

Unrecoverable Application Error or General Protection Fault when

you call lstrcpy.

The following is an example program that demonstrates the use of

lstrcpy to retrieve a LPSTR pointer returned from the Windows API

GetDOSEnvironment routine. Note that the capability of the Windows

API GetDOSEnvironment routine is already available through the

Environ function built into Visual Basic; therefore, the following

program mainly serves as an example of using lstrcpy.

'*** General declarations ***

Declare Function GetDosEnvironment Lib "Kernel" () As Long

' The following Declare statement must appear on one line.

Declare Function lstrcpy Lib "Kernel" (ByVal lpString1 As Any, ByVal

lpString2 As Any) As Long

'*** Form Click event code ***

Sub Form_Click()

    Dim lpStrAddress As Long,  DOSEnv$

    ' Allocate space to copy LPSTR into

    DOSEnv$ = Space$(4096)

    ' Get address of returned LPSTR into a long integer

    lpStrAddress = GetDOSEnvironment()

    ' Copy LPSTR into a Visual Basic string

    lpStrAddress = lstrcpy(DOSEnv$, lpStrAddress)

    ' Parse first entry in environment string and print

    DOSEnv$ = RTrim$(Left$(DOSEnv$, Len(DOSEnv$) - 1))

    Form1.Print DOSEnv$

End Sub


VB CAN DETERMINE WHEN A SHELLED PROCESS HAS TERMINATED
VB CAN DETERMINE WHEN A SHELLED PROCESS HAS TERMINATED	Q72880

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

The Shell function initiates a process and returns back to the Visual

Basic program. The process will continue indefinitely until you decide

to stop it. Terminating the Visual Basic program will not cause the

shelled process to terminate; however, you may not want this behavior

if you want the Visual Basic program to wait until the shelled process

has finished before continuing. This article describes a method by

which a Visual Basic program will wait until a shelled process has

terminated.

More Information:

By using the Windows API functions GetActiveWindow and IsWindow, your

program can monitor the status of a shelled process. The API function

GetActiveWindow should be called from within a loop after the Shell

function to get the window handle of the main application window for

the shelled process. This will work correctly only if you invoke the

Shell function using a window style with focus (that is, window style

1, 2, or 3), and a main application window is displayed for the

shelled process. This routine will work when shelling to Windows or

MS-DOS programs. It will not work for applications that do not

display a window (such as applications that run invisibly in the

background).

By continually calling the API function IsWindow from within a While

loop, you can make the Visual Basic program wait until the shelled

process has terminated. The Windows API function IsWindow simply

checks to make sure that the window associated with the handle found

with GetActiveWindow is still a valid, existing window.

Below are the steps necessary to build a Visual Basic program that

uses the Shell function to execute the Windows Calculator accessory.

The program is an example of how to use the Windows API functions

GetActiveWindow and IsWindow to wait until a shelled process has

terminated before resuming execution.

Code Example

------------

1. Run Visual Basic, or from the File menu, choose New Project (ALT,

   F, N) if Visual Basic is already running. Form1 is created by

   default.

2. Add the following code to the general Declarations section of Form1:

      DefInt A-Z

      Declare Function GetActiveWindow Lib "User" ()

      Declare Function IsWindow Lib "User" (ByVal hWnd)

3. Add the following code to the Form_Load event procedure of Form1:

   Sub Form_Load ()

       form1.Show	' Show the form: This will cause the hWnd

' property for Form1 to become valid.

       TimeOutPeriod = 5	' Maximum seconds to wait for application

' window to appear.

       r = Shell("calc.exe", 1)	' Must Shell using a Window Style

' with focus, Window style 1, 2,

' or 3.

       ' Wait for the application window of the shelled process

       ' to become active.

       fTimeOut = False

       s! = Timer

       Do

           r = DoEvents()	' Process Windows events for the shelled

' application.

' WARNING: Calling DoEvents allows the

' user to select any window. If the user

' selects another window, this routine

' will incorrectly treat that window as

' part of the shelled process.

           hWndShelledWindow = GetActiveWindow()

           ' Set timeout flag if time has expired.

           If Timer - s! > TimeOutPeriod Then fTimeOut = True

       Loop While hWndShelledWindow = form1.hWnd And Not fTimeOut

       ' If a timeout occurred, display a timeout message and

       ' terminate.

       If fTimeOut Then

           MsgBox "Timeout waiting for shelled application", 16

           End

       End If

       While IsWindow(hWndShelledWindow)	' Wait until the shelled

' process has terminated.

           r = DoEvents()	' Process pending Windows events.

       Wend

       MsgBox "Shelled application just terminated", 64

       End

   End Sub


HOW TO GET WINDOWS MASTER LIST (TASK LIST) USING VISUAL BASIC
HOW TO GET WINDOWS MASTER LIST (TASK LIST) USING VISUAL BASIC	Q78001

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

By calling the Windows API functions GetWindow, GetWindowText, and

GetWindowTextLength, you can get the window titles of all windows

(visible and invisible) loaded under Windows. The list of all of the

window titles under Windows is known as the master list. The Windows

Task Manager contains a list of the window titles for each of the

top-level windows (normally one per application). This list is known

as the task list.

Listed below is a sample program that demonstrates how to AppActivate

an application that is available from a list of top-level windows.

More Information:

The task list is generally a subset of the master list. The Windows

API functions only support methods of getting the master list, not the

task list. However, from the master list you can get a list of all

top-level windows closely resembling the task list. The only

difference is that the list containing the top-level windows may have

more entries than the task list. The reason for this is that it is

possible for an application to remove itself from the task list, but

it will be included as part of the master list.

The example below demonstrates how to get the names of all top-level

windows. The names of child windows can also be obtained by calling

the GetWindow API function with the GW_CHILD constant. Although the

code example only provides an example of using the constants

GW_HWNDFIRST and GW_HWNDNEXT as arguments to GetWindow, the value of

the other constants such as GW_CHILD are provided in the code.

Below are the steps necessary to construct a sample program that

demonstrates how to load the task list into a Visual Basic combo

box:

1. Run Visual Basic, or choose New Project from the File menu (ALT, F,

   N) if Visual Basic is already running. Form1 will be created by

   default.

2. Change the caption property of Form1 to AppActivate.

3. Add the following controls to Form1 and change the Names as

   indicated in the chart below:

   Control	Default Name	Name

   -------	------------	-------

   Label Control	Label1	Label1

   Combo Box	Combo1	Combo_ListItem

   Command Button	Command1	Command_Ok

4. Change the Caption properties of the controls as follows:

   Control	CtlName	Caption

   -------	-------	---------

   Label Control	Label1	Application to AppActivate:

   Command Button	Command_OK	OK

5. Add the following code to the general declarations section of

   Form1:

    DefInt A-Z

    '* Windows API function declarations

    Declare Function GetWindow Lib "user" (ByVal hWnd, ByVal wCmd) As

Integer

    Declare Function GetWindowText Lib "user" (ByVal hWnd, ByVal

lpSting$, ByVal nMaxCount) As Integer

    Declare Function GetWindowTextLength Lib "user" (ByVal hWnd)

As Integer

    '* Declare constants used by GetWindow

    Const GW_CHILD = 5

    Const GW_HWNDFIRST = 0

    Const GW_HWNDLAST = 1

    Const GW_HWNDNEXT = 2

    Const GW_HWNDPREV = 3

    Const GW_OWNER = 4

6. Add the following code in the Form_Load event procedure of Form1:

     Sub Form_Load ()

       Call LoadTaskList

       '* Check to see if any items are in the task list, if

       '* not end the program.

       If Combo_ListItem.ListCount > 0 Then

           Combo_ListItem.Text = Combo_ListItem.List(0)

       Else

           MsgBox "Nothing found in task list", 16, "AppActivate"

           Unload Form1

       End If

     End Sub

7. Enter the following code in the Click event procedure of the

   Command_Ok button:

     Sub Command_Ok_Click ()

           '* Get the item selected from the text portion of the

           '* combo box.

           f$ = Combo_ListItem.Text

           '* Simply resume if an "Illegal function call" occurs on

           '* the AppActivate statement.

           On Local Error Resume Next

           AppActivate f$

     End Sub

8. Enter the following code under the general declarations section of

   Form1:

     Sub LoadTaskList ()

' Get the hWnd of the first item in the master list

' so we can process the task list entries (top-level only).

CurrWnd = GetWindow(Form1.hWnd, GW_HWNDFIRST)

' Loop while the hWnd returned by GetWindow is valid.

While CurrWnd <> 0

'* Get the length of the task name identified by

'* CurrWnd in the list.

Length = GetWindowTextLength(CurrWnd)

'* Get the task name of the task in the master list.

ListItem$ = Space$(Length + 1)

Length = GetWindowText(CurrWnd, ListItem$, Length + 1)

'* If there is an actual task name in the list, add the

'* item to the list.

If Length > 0 Then

Combo_ListItem.AddItem ListItem$

End If

'* Get the next task list item in the master list.

CurrWnd = GetWindow(CurrWnd, GW_HWNDNEXT)

'* Process Windows events.

x = DoEvents()

Wend

End Sub

9. From the Run menu, choose Start (ALT, R, S) to run the program.

From the combo box, select the window title of an application

currently running under Windows. Choose the OK button to activate the

application.


HOW TO USE WINDOWS 3.0 BITBLT FUNCTION FROM VISUAL BASIC
HOW TO USE WINDOWS BITBLT FUNCTION FROM VISUAL BASIC	Q71104

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

The Windows GDI.DLL has a function called BitBlt, which will move the
source device given by the hSrcDC parameter to the destination device
given by the hDestDC parameter. This article explains in detail the
arguments of the Windows BitBlt function call.

More Information:

To use BitBlt within a Visual Basic application, you must Declare the
BitBlt function in either the Global section (if using Visual Basic
version 1.0), within the (declaration) section of any code module (if
using Visual Basic 2.0) or within the (declaration) section of a code
window for the form.  Declare the Function as follows:

Declare Function BitBlt Lib "gdi"	(ByVal hDestDC%,

ByVal X%, ByVal Y%,

ByVal nWidth%,

ByVal nHeight%,

ByVal hSrcDC%,

ByVal XSrc%, ByVal YSrc%,

ByVal dwRop&) As Integer

Note: The above Declare statement must be written on just one line.

The following formal parameters are defined as:

   Formal Parameter	Definition

   ----------------	----------

   hDestDC	Specifies the device context that is to
receive the bitmap.

   X,Y	Specifies the logical x-coordinate and
y-coordinate of the upper-left corner of the

destination rectangle.

   nWidth	Specifies the width (in logical units) of the

destination rectangle and the source bitmap.

   nHeight	Specifies the height (in logical units) of

the destination rectangle and the source

bitmap.

   hSrcDC	Identifies the device context from which the

bitmap will be copied. It must be

NULL(zero) if the dwRop& parameter specifies

a raster operation that does not include a

source.

   XSrc	Specifies the logical x-coordinate and the

y-coordinate of the upper-left corner of the

source bitmap.

  dwRop	Specifies the raster operation to be performed

as defined below.

The following Raster operations are defined using the predefined
constants found in the WINDOWS.H file supplied with the Microsoft

Windows Software Development Kit (SDK). The value

within the "()" is the value to assign to the dwRop& variable.

   Code/Value (hex)	Description

   ----------------	-----------

   BLACKNESS (42)	Turn output black.

   DSINVERT(550009)	Inverts the destination bitmap.

   MERGECOPY(C000CA)	Combines the pattern and the source bitmap

using the Boolean AND operation.

   MERGEPAINT(BB0226)	Combines the inverted source bitmap with the

destination bitmap using the Boolean OR

operator.

   NOTSRCCOPY(330008)	Copies the inverted source bitmap to the

destination.

   NOTSRCERASE(1100A6)	Inverts the result of combining the

destination and source bitmap using the

Boolean OR operator.

   PATCOPY(F00021)	Copies the pattern to the destination bitmap.

   PATINVERT(5A0049)	Combines the destination bitmap with the

pattern using the Boolean XOR operator.

   PATPAINT(FB0A09)	Combines the inverted source bitmap with the

pattern using the Boolean OR operator.

Combines the result of this operation with

the destination bitmap using the Boolean OR

operator.

   SRCAND(8800C6)	Combines pixels of the destination and source

bitmap using the Boolean AND operator.

   SRCCOPY(CC0020)	Copies the source bitmap to the destination

bitmap.

   SRCERASE(4400328)	Inverts the destination bitmap and combines

the results with the source bitmap using the

Boolean AND operator.

   SRCINVERT(660046)	Combines pixels of the destination and source

bitmap using the Boolean XOR operator.

   SRCPAINT(EE0086)	Combines pixels of the destination and source

bitmap using the Boolean OR operator.

   WHITENESS(FF0062)	Turns all output white.

Below is an example of how to copy the contents of a picture control

to the contents of another picture control.

Define a form with two picture controls. Display some graphics on

Picture1 by loading from a picture file or pasting from the clipboard

at design time. You can load a picture from a file as follows: from

the Properties bar, select Picture from the Properties list box and

click the arrow at the right of the Settings box, then select the

desired picture file (such as a .BMP or .ICO file supplied with

Microsoft Windows) from the dialog box.

Add the following code to the Form_Click procedure. Run the program

and click the form. The contents of the first picture will be

displayed to the second picture.

Sub Form_Click ()

   ' Assign information of the destination bitmap. Note that Bitblt

   ' requires coordinates in pixels.

   Const PIXEL = 3

   Picture1.ScaleMode = PIXEL

   Picture2.ScaleMode = PIXEL

   hDestDC% = Picture2.hDC

   X% = 0: Y% = 0

   nWidth% = Picture2.ScaleWidth

   nHeight% = Picture2.ScaleHeight

   ' Assign information of the source bitmap.

   hSrcDC% = Picture1.hDC

   XSrc% = 0: YSrc% = 0

   ' Assign the SRCCOPY constant to the Raster operation.

   dwRop& = &HCC0020

   Suc% = BitBlt(hDestDC%, X%, Y%, nWidth%, nHeight%,_

hSrcDC%, XSrc%, YSrc%, dwRop&)

End Sub

References:

1. "Programming Windows: the Microsoft Guide to Writing Applications

   for Windows 3," by Charles Petzold (published by Microsoft

   Press, 1990)

2. "Microsoft Windows 3.0 Software Development Kit: Reference

   Volume 1"

3. The WINSDK.HLP file shipped with Microsoft Windows 3.0 Software

   Development Kit.


HOW VB CAN DETERMINE IF A SPECIFIC WINDOWS PROGRAM IS RUNNING
HOW VB CAN DETERMINE IF A SPECIFIC WINDOWS PROGRAM IS RUNNING	Q72918

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

To determine if a specific program is running, call the Windows API

function FindWindow. FindWindow returns the handle of the window whose

class is given by the lpClassname parameter and whose window name, or

caption, is given by the lpCaption parameter. If the returned value is

zero, the application is not running.

More Information:

By calling FindWindow with a combination of a specific program's class

name and/or the title bar caption, your program can determine whether

that specific program is running.

When an application is started from the Program Manager, it registers

the class name of the form. The window class provides information

about the name, attributes, and resources required by your form. All

Visual Basic forms have a class name of "ThunderForm." You can

determine the class name of an application by using the SPY.EXE program

that comes with the Microsoft Windows version 3.0 Software Development

Kit (SDK).

If the window has a caption bar title, you can also use the title to

locate the instance of the running application. This caption text is

valid even when the application is minimized to an icon.

Because another instance of your Visual Basic program will have the

same class name and may have the same title bar caption, you must use

dynamic data exchange (DDE) to determine if another instance of your

Visual Basic program is running. (This DDE technique is not shown in

this article).

The following example shows three ways to determine if the Windows

version 3.x Calculator is running. To create the program, perform the

following steps:

1. Create a form.

2. Declare the Windows version 3.x API function FindWindow in the

   General-Declarations section of the code window. The variables are

   declared as "Any" because you can pass either a pointer to a string,

   or a BLANK value. You as a programmer are responsible for passing

   the correct variable type. Note that the Declare statement should

   be entered on just one line:

   Declare Function FindWindow% Lib "user" (ByVal lpClassName As Any,

ByVal lpCaption As Any)

3. Add the following code to the form's Click event. This example

   demonstrates how you can find the instance of the application with a

   combination of the class name and/or the window's caption. In this

   example, the application will find an instance of the Windows

   version 3.x calculator (CALC.EXE) program.

Sub Form_Click ()

   Const BLANK = 0&

   lpClassName$ = "SciCalc"

   lpCaption$ = "Calculator"

   Print "Handle = ";FindWindow(lpClassName$, BLANK)

   Print "Handle = ";FindWindow(BLANK, lpCaption$)

   Print "Handle = ";FindWindow(lpClassName$,lpCaption$)

End Sub

4. Run this program with CALC.EXE running and without CALC.EXE

   running. If CALC.EXE is running, your application will print an

   arbitrary handle. If CALC.EXE is not running, your application will

   print the number zero as a handle.

Below are some class names of applications that are shipped with

Windows version 3.x:

Class Name	Application

-----------	-----------

SciCalc	CALC.EXE

CalWndMain	CALENDAR.EXE

Cardfile	CARDFILE.EXE

Clipboard	CLIPBOARD.EXE

Clock	CLOCK.EXE

CtlPanelClass	CONTROL.EXE

XLMain	EXCEL.EXE

Session	MS-DOS.EXE

Notepad	NOTEPAD.EXE

pbParent	PBRUSH.EXE

Pif	PIFEDIT.EXE

PrintManager	PRINTMAN.EXE

Progman	PROGMAN.EXE   (Windows Program manager)

Recorder	RECORDER.EXE

Reversi	REVERSI.EXE

#32770	SETUP.EXE

Solitaire	SOL.EXE

Terminal	TERMINAL.EXE

WFS_Frame	WINFILE.EXE

MW_WINHELP	WINHELP.EXE

#32770	WINVER.EXE

OpusApp	WINWORD.EXE

MSWRITE_MENU	WRITE.EXE

Reference(s):

"Programming Windows: the Microsoft Guide to Writing Applications

for Windows 3," Charles Petzold. Microsoft Press, 1990.

"Peter Norton's Windows 3.0 Power Programming Techniques," Peter

Norton and Paul Yao. Bantam Computer Books, 1990.

"Microsoft Windows 3.0 Software Development Kit: Reference Volume 1."

WINSDK.HLP file shipped with Microsoft Windows SDK version 3.0.


EXAMPLE OF CLIENT/SERVER DDE BETWEEN VISUAL BASIC APPLICATIONS
EXAMPLE OF DDE BETWEEN VISUAL BASIC APPLICATIONS	Q74861

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

This article outlines the steps necessary to initiate dynamic data

exchange (DDE) between a Microsoft Visual Basic destination application and a Visual Basic source application.

This article demonstrates how to:

 - Create a Visual Basic application to function as a DDE source.

 - Create a Visual Basic application to function as a DDE destination.

 - Initiate a manual DDE link (information updated upon request from the

   destination) between the destination application and the source

   application.

 - Use LinkRequest to update information in the destination application

   from information in the source application.

 - Initiate a automatic DDE link (information updated automatically from

   source to destination) between the destination application and the

   source application.

 - Use LinkPoke to send information from the destination application to

   the source application.

 - Change the LinkMode property between automatic and manual.

More Information:

A destination application sends commands through DDE to the source

application to establish a link. Through DDE, the source provides data

to the destination at the request of the destination or accepts information at the request of the destination.

Example

-------

The steps below are an example of how to establish a DDE conversation

between two Visual Basic applications.

First, create the source application in Visual Basic:

1. Start Visual Basic, and Form1 will be created by default.

2. Change the Caption property of Form1 to "Source".

3. Put a Text Box (Text1) on Form1.

4. Save the form and project with the name SOURCE.

5. From the File menu, choose Make EXE File. In the Make EXE File

   dialog box, choose OK to accept SOURCE.EXE as the name of the EXE

   file.

Second, create the destination application in Visual Basic:

1. From the File menu, choose New Project. Form1 will be created by

   default.

2. Change the Caption property of Form1 to "Destination".

3. Create the following controls with the following properties on

   Form1:

     Default Name	Caption	Name

     ------------	-------	-------

     Text1	(Not applicable)	Text1

     Option1	Manual Link	ManualLink

     Option2	Automatic Link	AutomaticLink

     Command1	Poke	Poke

     Command2	Request	Request

4. Add the following code to the General Declaration section of Form1:

      Const AUTOMATIC= 1

      Const MANUAL = 2

      Const NONE = 0

      (NOTE:  For Visual Basic version 1.0, also add the following

              constants:

      Const TRUE = -1

      Const FALSE = 0

5. Add the following code to the Load event procedure of Form1:

Sub Form_Load ()

    'This procedure will start the VB source application that was

    'created earlier

    z% = Shell("SOURCE", 1)

    z% = DoEvents()	'Causes Windows to finish

'processing the Shell command.

    Text1.LinkMode = NONE	'Clears DDE link if it already

'exists.

    Text1.LinkTopic = "Source|Form1"	'Sets up link with VB source.

    Text1.LinkItem = "Text1"	'Set link to text box on source.

    Text1.LinkMode = MANUAL	'Establish a manual DDE link.

    ManualLink.Value = TRUE	'Sets appropriate option button.

End Sub

6. Add the following code to the Click event procedure of ManualLink:

Sub ManualLink_Click ()

    Request.Visible = TRUE	'Make request button valid.

    Text1.LinkMode = NONE	'Clear DDE Link.

    Text1.LinkMode = MANUAL	'Reestablish new LinkMode.

End Sub

7. Add the following code to the Clink event procedure of AutomaticLink:

Sub AutomaticLink_Click ()

    Request.Visible = FALSE	'No need for button with automatic link.

    Text1.LinkMode = NONE	'Clear DDE Link.

    Text1.LinkMode = AUTOMATIC	'Reestablish new LinkMode.

End Sub

8. Add the following code to the Click event procedure of Request:

Sub Request_Click ()

    'With a manual DDE link, this button will be visible, and when

    'selected it will request an update of information from the source

    'application to the destination application.

    Text1.LinkRequest

End Sub

9. Add the following code to the Click event procedure of Poke:

Sub Poke_Click ()

    'With any DDE link, this button will be visible, and when it's

    'selected, will poke information from the destination application

    'into the source application.

    Text1.LinkPoke

End Sub

You can now run the Visual Basic destination application from the VB.EXE

environment (skip to step 4 below) or you can save the application and

create an .EXE file and run that from Windows (continue to step 1

below).

1. From the File menu, choose Save and save the form and project with

   the name DEST.

2. From the File menu, choose Make EXE File with the name

   DEST.EXE.

3. Exit the Visual Basic environment (VB.EXE).

4. Run the application (from Windows if an .EXE file, or from the Run

   menu if from the VB.EXE environment.)

5. Form1 of the destination application will load and the source

   application will automatically start.

You can now experiment with DDE between Visual Basic applications:

1. Try typing some text into the source's text box and then click the

   Request button. The text appears in the destination's text box.

2. Click the Automatic Link button and then type some more text into the

   source's text box. The text is automatically updated in the

   destination's text box.

3. Type some text into the destination's text box and click the Poke

   button. The text is sent to the source's text box.

(NOTE: You can also establish DDE between applications at design time, as described on page 356 of the "Microsoft Visual Basic: Programmer's

Guide" version 1.0 manual.)


DDE EXAMPLE BETWEEN VISUAL BASIC AND WORD FOR WINDOWS
DDE EXAMPLE BETWEEN VISUAL BASIC AND WORD FOR WINDOWS	Q74862

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

This article outlines the steps necessary to initiate dynamic data

exchange (DDE) between a Microsoft Visual Basic application and a

Microsoft Word for Windows (WINWORD.EXE) document at run time.

This article demonstrates how to:

1. Prepare a Word for Windows document for active DDE.

2. Initiate a manual DDE link (information updated upon request from

   the destination) between the Visual Basic application (the

   destination) and the document loaded into Word for Windows (the

   source).

3. Use LinkRequest to update information in the Visual Basic destination

   based on information contained in the Word for Windows source.

4. Initiate a automatic DDE link (information updated automatically from

   source to destination) between the Visual Basic destination and the

   Word for Windows source.

5. Use LinkPoke to send information from the Visual Basic destination to

   the Word for Windows source.

6. Change the LinkMode property between automatic and manual.

More Information:

A destination application sends commands through DDE to the source

application to establish a link. Through DDE, the source provides data

to the destination at the request of the destination or accepts information at the request of the destination.

Example

-------

The steps below are an example of how to establish a DDE conversation

between a Visual Basic application and a document loaded into Word for

Windows (WINWORD.EXE).

First, create the source document in Word for Windows:

1. Start Word for Windows. "Document1" will be created by default.

2. From the Window menu, choose Arrange All. This unmaximizes the

   document if it was maximized. Note that the title at the top of the

   WINWORD.EXE main title bar is now "Microsoft Word" and NOT

   "Microsoft Word - Document1".

3. Press CTRL+SHIFT+END to select to the end of the document.

4. From the Insert menu, choose Bookmark. Under Bookmark Name, type

   "DDE_Link" (without quotation marks). Press ENTER. This sets a

   bookmark for the entire document. This bookmark will function as

   the LinkItem in the DDE conversation.

5. From the File menu, choose Save As, and save the document with the

   name SOURCE.DOC.

6. Exit Word for Windows. For this particular example to function

   properly, WINWORD.EXE must not be loaded and running.

Second, create the destination application in Visual Basic:

1. Start Visual Basic. Form1 will be created by default.

2. Create the following controls with the following properties on

   Form1:

   Default Name	Caption	Name

   ------------	-------	-------

   Text1	(Not applicable)	Text1

   Option1	Manual Link	ManualLink

   Option2	Automatic Link	AutomaticLink

   Command1	Poke	Poke

   Command2	Request	Request

3. Add the following code to the General Declaration section of Form1:

      Const AUTOMATIC = 1

      Const MANUAL = 2

      Const NONE = 0

4. Add the following code to the Load event procedure of Form1:

Sub Form_Load ()

    'This procedure will start WINWORD.EXE, load the document that was

    'created earlier and prepared for DDE by creating a bookmark to

    'the whole document.  This bookmark is necessary because it

    'functions as the LinkItem for the source in the DDE conversation.

    z% = Shell("WinWord Source.Doc",1)

    z% = DoEvents ()	'Process Windows events. This ensures

'that WinWord will be executed before

'any attempt is made to perform DDE

'with it.

    Text1.LinkMode = NONE	'Clears DDE link if it already exists.

    Text1.LinkTopic = "WinWord|Source"	'Sets up link with

'WINWORD.EXE.

    Text1.LinkItem = "DDE_Link"	'Set link to bookmark on document.

    Text1.LinkMode = MANUAL	'Establish a manual DDE link.

    ManualLink.Value = TRUE

End Sub

5. Add the following code to the Click event procedure of the Manual

   Link button:

Sub ManualLink_Click ()

        Request.Visible = TRUE	'Make request button valid.

        Text1.LinkMode = NONE	'Clear DDE Link.

        Text1.LinkMode = MANUAL	'Reestablish new LinkMode.

End Sub

6. Add the following code to the Click event procedure of the Automatic

   Link button:

Sub AutomaticLink_Click ()

        Request.Visible = FALSE	'No need for button with automatic

'link.

        Text1.LinkMode = NONE	'Clear DDE Link.

        Text1.LinkMode = AUTOMATIC	'Reestablish new LinkMode.

End Sub

7. Add the following code to the Click event procedure of the Request

   button:

Sub Request_Click ()

    'With a manual DDE link this button will be visible, and clicking

    'this button will request an update of information from the source

    'application to the destination application.

    Text1.LinkRequest

End Sub

8. Add the following code to the Click event procedure of the Poke

   button:

Sub Poke_Click ()

    'With any DDE link, this button will be visible, and clicking

    'this button will poke information from the destination application

    'into the source application.

    Text1.LinkPoke

End Sub

You can now run the Visual Basic destination application from the

Visual Basic VB.EXE environment (skip to step 4 below) or you can save

the application and create an EXE file and run that from Windows

(continue to step 1 below).

1. From the File menu, choose Save and save the form and project with

   the name DEST.

2. From the File menu, choose Make EXE File with the name DEST.EXE.

3. Exit the Visual Basic environment (VB.EXE).

4. Run the application (from Windows if an .EXE file or from the Run

   menu if from the Visual Basic environment.)

   Form1 of the Visual Basic destination application will be loaded,

   and Word for Windows will automatically be started with the document

   SOURCE.DOC loaded.

5. Make sure that the main title bar in WINWORD.EXE reads "Microsoft

   Word", NOT "Microsoft Word - SOURCE.DOC". If the title bar is not

   correct, choose Arrange All from the Window menu.

You can now experiment with DDE between Visual Basic and Word

for Windows:

1. Try typing some text into the document in Word for Windows, and

   then click the Request button. The text appears in the text box.

2. Click Automatic Link and then type some more text into the document

   in Word for Windows. The text is automatically updated in the Visual

   Basic text box.

3. Type some text in the text box in the Visual Basic application and

   click the Poke button. The text is sent to the document in Word for

   Windows.

Note that if in the WINWORD.EXE document, you delete the total

contents of the bookmark, the bookmark will also be deleted. Any

further attempt to perform DDE with this WINWORD.EXE session after the

bookmark has been deleted gives the following error message:

   Foreign applications won't perform DDE method or operation.

If this happens, you must recreate the bookmark in the document in

Word for Windows before performing any further DDE operations.

You can also establish DDE between applications at design time. This

is described on page 356 of the "Microsoft Visual Basic: Programmer's

Guide" version 1.0 manual.

For Visual Basic 1.0 add two global constants in the general declarations of the form

CONST TRUE = -1

CONST FALSE = NOT TRUE


DDE FROM VISUAL BASIC TO EXCEL FOR WINDOWS
DDE FROM VISUAL BASIC TO EXCEL FOR WINDOWS	Q75089

See Also

This article reprinted from the Microsoft Product Support KnowledgeBase.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 1.0 and 2.0.

Summary:

This article describes how to initiate a dynamic data exchange (DDE)

conversation between a Visual Basic destination application and a Microsoft Excel source application.

This article demonstrates how to:

 - Prepare a Microsoft Excel for Windows document for active DDE.

 - Initiate a manual DDE link (information updated upon request from

   the destination) between Visual Basic (the destination) and Excel

   (the source).

 - Use the LinkRequest method to update information in Visual Basic

   (the destination) based on information contained in Excel (the

   source).

 - Initiate a automatic DDE link (information updated automatically

   from source to destination) between Visual Basic (the destination)

   and Excel (the source).

 - Use the LinkPoke method to send information from Visual Basic (the

   destination) to Excel (the source).

 - Change the LinkMode property between automatic and manual.

More Information:

A destination application sends commands through DDE to the source

application to establish a link. Through DDE, the source provides data

to the destination at the request of the destination or accepts information at the request of the destination.

The procedure below is as an example of how to establish a DDE

conversation between Visual Basic and Excel for Windows.

First, create the source spreadsheet in Excel:

1. Start Excel, and a document titled "SHEET1" will be created by

   default.

2. From the File menu, choose Save As, and save the document with the

   name SOURCE.XLS

4. Exit Excel. For this example to function properly, Excel must not

   be loaded and running.

Next, create the destination application in Visual Basic:

The destination is the application that performs the link operations. It prompts the source to send information or informs the source that

information is being sent.

1. Start Visual Basic (VB.EXE), and Form1 will be created by default.

2. Create the following controls with the following properties on

   Form1:

      Default Name	Caption	Name

      ------------	-------	-------

      Text1	(not applicable)	Text1

      Option1	Manual Link	ManualLink

      Option2	Automatic Link	AutomaticLink

      Command1	Poke	Poke

      Command2	Request	Request

3. Add the following code to the general Declaration section of Form1:

      Const AUTOMATIC = 1

      Const MANUAL = 2

      Const NONE = 0

4. Add the following code to the Load event procedure of Form1:

Sub Form_Load ()

    'This procedure will start Excel and load SOURCE.XLS, the

    'spreadsheet that was created earlier.

    z% = Shell("EXCEL SOURCE.XLS", 1)

    z% = DoEvents()	'Process Windows events. This ensures

'that Excel will be executed before

'any attempt is made to perform DDE.

    Text1.LinkMode = NONE	'Clears DDE link if it already exists.

    Text1.LinkTopic = "Excel|source.xls"	'Sets up link

'with Excel.

    Text1.LinkItem = "R1C1"	'Set link to first cell on spreadsheet.

    Text1.LinkMode = MANUAL	'Establish a manual DDE link.

    ManualLink.Value = TRUE

End Sub

5. Add the following code to the Click event procedure of the

   Manual Link button:

Sub ManualLink_Click ()

        Request.Visible = TRUE	'Make request button valid.

        Text1.LinkMode = NONE	'Clear DDE Link.

        Text1.LinkMode = MANUAL	'Reestablish new LinkMode.

End Sub

6. Add the following code to the Click event procedure of the

   Automatic Link button:

Sub AutomaticLink_Click ()

        Request.Visible = FALSE	'No need for button with automatic

'link.

        Text1.LinkMode = NONE	'Clear DDE Link.

        Text1.LinkMode = AUTOMATIC	'Reestablish new LinkMode.

End Sub

7. Add the following code to the Click event procedure of the

   Request button:

Sub Request_Click ()

   'With a manual DDE link this button will be visible and when

   'selected it will request an update of information from the source

   'application to the destination application.

    Text1.LinkRequest

End Sub

8. Add the following code to the Click event procedure of the Poke

   button:

Sub Poke_Click ()

    'With any DDE link this button will be visible and when selected

    'it will poke information from the destination application to the

    'source application.

    Text1.LinkPoke

End Sub

You can now run the Visual Basic destination application from the Visual Basic environment (skip to step 4 below) or you can save the

application and create an .EXE file and run that from Windows (start

from step 1 below):

1. From the Visual Basic File menu, choose Save, and save the Form and

   Project with the name DEST.

2. From the File menu, choose Make EXE File, and name it DEST.EXE.

3. Exit Visual Basic.

4. Run the application (from Windows if an .EXE file or from the Run

   menu if from the Visual Basic environment).

5. Form1 of the destination application will be loaded and Excel will

   automatically be started with the document SOURCE.XLS loaded.

6. Make sure the main title bar in Excel reads "Microsoft Excel," NOT

   "Microsoft Excel - SOURCE.XLS." If the title bar is incorrect, then

   from the Window menu choose Arrange All.

You can now experiment with DDE between Visual Basic and Excel:

1. Try typing some text in R1C1 in the spreadsheet and then select the

   Request button. The text appears in the text box.

   Be sure to press the ENTER key after entering text into an Excel

   cell before clicking the Request button in the Visual Basic

   program, or else a "Timeout while waiting for DDE response" error

   message will be displayed from the TEXT1.LINKREQUEST statement.

   This occurs because while entering text into a cell, Excel is in a

   polling loop for data entry, and no real data is transferred to the

   cell until you press ENTER. Therefore, Visual Basic keeps

   attempting to request the data from the cell, but Excel does not

   pay attention to the request until it exits the polling loop, which

   results in the DDE time-out message.

2. Choose the Automatic Link button and then type some more text in

   R1C1 of the spreadsheet. The text is automatically updated in the

   Visual Basic text box.

3. Type some text in the text box in the Visual Basic application and

   choose the Poke button. The text is sent to R1C1 in the Excel

   spreadsheet.

Note: If you have the Ignore Remote Requests option selected in the

Excel Workspace dialog box, you will not be able to establish DDE from

Visual Basic. Make sure the Ignore Remote Requests option is NOT

selected.

(NOTE: You can also establish DDE between applications at design time.

This is described on page 356 of the "Microsoft Visual Basic:

Programmer's Guide" version 1.0 manual.)

For Visual Basic 1.0 add the following constants to the general

declarations of the form:

CONST TRUE = -1

CONST FALSE = NOT TRUE


Form

See Also	Properties	Events	Methods

Description

A form is a window or dialog box that makes up part of an application's interface.

Remarks

Forms have properties that determine aspects of their appearance, such as position, size, and color, and aspects of their behavior, such as whether they are resizable.

Forms can also respond to events initiated by the user or triggered by the system.  For example, you could write code in a form's Click event procedure that would allow the user to change the color of a form by clicking it.

In addition to properties and events, you can use methods to manipulate forms from code.  For example, you can use the Move method to change a form's location and size.

A special kind of form, the MDI form, can contain other forms called MDI child forms.  An MDI form is created with the New MDI Form command on the File menu; an MDI child form is created by choosing New Form from the File menu and then setting the MDIChild property to True.

You can create multiple instances of forms in code by using the New reserved word in Dim, Global, Set, and Static statements.

When designing forms, set the BorderStyle property to define a form's border and set the Caption property to put text in the title bar.  In code, you can use the Hide and Show methods to make forms invisible or visible at run time.  Note, however, that you cannot use Hide on an MDI child form.

Form is an object type.  You can declare variables as type Form before setting them to an instance of a type of form that was declared at design time.  Similarly, you can declare a parameter to a procedure as type Form.

Forms also can be server links in a DDE conversation, with a label, picture box, or text box control furnishing the data.


Properties

ActiveControl	FontBold	LinkTopic

ActiveForm	FontItalic	MaxButton

AutoRedraw	FontName	MDIChild

BackColor	FontSize	MinButton

BorderStyle	FontStrikethru	MousePointer

Caption	FontTransparent	Name

ClipControls	FontUnderline	Picture

ControlBox	ForeColor	ScaleHeight

Count	hDC	ScaleLeft

CurrentX	Height	ScaleMode

CurrentY	HelpContextID	ScaleTop

DrawMode	hWnd	ScaleWidth

DrawStyle	Icon	Tag

DrawWidth	Image	Top

Enabled	KeyPreview	Visible

FillColor	Left	Width

FillStyle	LinkMode	WindowState


Events

Activate	KeyPress	MouseDown

Click	KeyUp	MouseMove

DblClick	LinkClose	MouseUp

Deactivate	LinkError	Paint

DragDrop	LinkExecute	QueryUnload

DragOver	LinkOpen	Resize

GotFocus	Load	Unload

KeyDown	LostFocus


Methods

Circle	PrintForm	Show

Cls	Print	TextHeight

Hide	PSet	TextWidth

Line	Refresh	ZOrder

Move	SetFocus

Point	Scale


See Also

Help:

Controls

Forms Collection

MDIForm

Using DDE

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 5 , "Managing Projects"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Controls

See Also	Controls List

Description

A control is an object that you draw on a form to enable or enhance user interaction with an application.  You add menu controls to a form using the Menu Design window; all other controls appear in the Toolbox and are placed on a form by double-clicking them or by clicking and then dragging them onto a form.

Remarks

Controls accept user input or display output.  Controls have properties that define aspects of their appearance, such as position, size, and color, and aspects of their behavior, such as how they respond to user input.

Controls can respond to events initiated by the user or triggered by the system.  For example, you could write code in a command button's Click event procedure that would load a file or perform a calculation and then display the result.

In addition to properties and events, you can use methods to manipulate controls from code.  For example, you can use the Move method with some controls to change their location and size.

Each control has its own set of properties, events and methods.

Note that the Control keyword is an object type and you can use it to declare a variable of type Control before setting it to a specific control type.  You can also declare a procedure parameter to have type Control.

Graphical controls include the image, label, line, and shape controls.  These controls have fewer properties, events and methods than similar controls such as the picture box and text box.


Controls List

Control	Description

Check box	Gives the user a True/False or Yes/No option.

Combo box	Enables the user to make a selection by typing text into a text box or by selecting an item from a list.

Command button	Chosen by the user to begin or end a process.

Directory list box	Enables the user to select directories and paths at run time.

Drive list box	Enables the user to select valid disk drives at run time.

File list box	Enables the user to select files at run time.

Frame	Provides a functional grouping and container for other controls.

Grid	Provides a matrix of spreadsheet-type cells whose contents can be manipulated in code.  Grid is a custom control supplied with Visual Basic.

Horizontal scroll bar	Allows navigation through lists or forms; also can indicate position in a range.

Image	Displays a bitmap, icon, or metafile as a graphic.

Label	Displays text the user can't change.

Line	Displays itself as a horizontal, vertical, or diagonal line.

List box	Displays a list from which the user can select one or more items.

Menu	Displays a menu on a form.

OLE client	Allows embedding of, or linking to, other objects in the Windows environment [image] for example, objects created by draw, graphics, and spreadsheet applications.  OLE client is a custom control supplied with Visual Basic.

Option button	As part of a group of option buttons, displays multiple choices from which the user can select only one.

Picture box	Displays graphics that are drawn with Circle, Line, and Print methods, or that are loaded from a bitmap, icon, or metafile.  Can also act as a container for other controls.

Shape	Displays itself as a variety of shapes including boxes, circles, and so on.

Text box	Displays text that you specify or that the user types.

Timer	Enables you to run code at a specified time interval.

Vertical scroll bar	Allows navigation through lists or forms; also can indicate position in a range.


See Also

Help:

ActiveControl Property

ActiveForm Property

Controls Collection

Creating a Menu Bar

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Check Box Control

See Also	Properties	Events	Methods

Description

A check box displays an X when selected; the X disappears when the check box is cleared.  Use this control to give the user a True/False or Yes/No option.  You can use check boxes in groups to display multiple choices from which the user can select one or more.

Remarks

Check boxes and option buttons function similarly but with an important difference: any number of check boxes on a form can be selected at the same time.  In contrast, only one option button in a group can be selected.

To display text next to the check box, set the Caption property.  Use the Value property to determine the state of the box [image] selected, cleared, or unavailable.


Properties

Alignment	FontStrikethru	Parent

BackColor	FontUnderline	TabIndex

Caption	ForeColor	TabStop

DragIcon	Height	Tag

DragMode	HelpContextID	Top

Enabled	hWnd	Value

FontBold	Index	Visible

FontItalic	Left	Width

FontName	MousePointer

FontSize	Name


Events

Click	GotFocus	KeyUp

DragDrop	KeyDown	LostFocus

DragOver	KeyPress


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Combo Box Control

See Also	Properties	Events	Methods

Description

A combo box combines the features of a text box and a list box.  Use a combo box to give the user the choice of typing in the text box portion or selecting an item from the list portion of the control.


Properties

BackColor	HelpContextID	SelLength

DragIcon	hWnd	SelStart

DragMode	Index	SelText

Enabled	ItemData	Sorted

FontBold	Left	Style

FontItalic	List	TabIndex

FontName	ListCount	TabStop

FontSize	ListIndex	Tag

FontStrikethru	MousePointer	Text

FontUnderline	Name	Top

ForeColor	NewIndex	Visible

Height	Parent	Width


Events

Change	DragOver	KeyPress

Click	DropDown	KeyUp

DblClick	GotFocus	LostFocus

DragDrop	KeyDown


Methods

AddItem	Refresh

Clear	RemoveItem

Drag	SetFocus

Move	ZOrder


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Command Button Control

See Also	Properties	Events	Methods

Description

A command button is chosen by the user to begin, interrupt, or end a process.  When chosen, a command button appears pushed in, and is sometimes called a "push button."

Remarks

To display text on a command button, set its Caption property.  A user can always choose a command button by clicking it.  To allow the user to choose it by pressing Enter, set the Default property to True.  To allow the user to choose the button by pressing Esc, set the button's Cancel property to True.


Properties

BackColor	FontSize	Parent

Cancel	FontStrikethru	TabIndex

Caption	FontUnderline	TabStop

Default	Height	Tag

DragIcon	HelpContextID	Top

DragMode	hWnd	Value

Enabled	Index	Visible

FontBold	Left	Width

FontItalic	MousePointer

FontName	Name


Events

Click	KeyDown

DragDrop	KeyPress

DragOver	KeyUp

GotFocus	LostFocus


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Directory List Box Control

See Also	Properties	Events	Methods

Description

A directory list box displays directories and paths at run time.  You can use this control to display a hierarchical list of directories.  This is useful if you want to create dialog boxes that, for example, enable the user to open a file from a list of files in all available directories.

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in a list.  If you also display a drive list box and file list box, you can write code to synchronize them with the directory list box and with each other.


Properties

BackColor	ForeColor	Name

DragIcon	Height	Parent

DragMode	HelpContextID	Path

Enabled	hWnd	TabIndex

FontBold	Index	TabStop

FontItalic	Left	Tag

FontName	List	Top

FontSize	ListCount	Visible

FontStrikethru	ListIndex	Width

FontUnderline	MousePointer


Events

Change	KeyPress

Click	KeyUp

DragDrop	LostFocus

DragOver	MouseDown

GotFocus	MouseMove

KeyDown	MouseUp


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Drawing a Control

Drive List Box Control

File List Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 18, "Using the File-System Controls"


Drive List Box Control

See Also	Properties	Events	Methods

Description

A drive list box enables the user to select a valid disk drive at run time.  You can use this control to display a list of all the valid drives in the user's system.  This is useful if you want to create dialog boxes that enable the user to open a file from a list of files on a disk in a different drive.

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.  If you also display a directory list box and file list box, you can write code to synchronize them with the drive list box and with each other.


Properties

BackColor	FontUnderline	MousePointer

DragIcon	ForeColor	Name

DragMode	HelpContextID	Parent

Drive	Height	TabIndex

Enabled	hWnd	TabStop

FontBold	Index	Tag

FontItalic	Left	Top

FontName	List	Visible

FontSize	ListCount	Width

FontStrikethru	ListIndex


Events

Change	KeyDown

DragDrop	KeyPress

DragOver	KeyUp

GotFocus	LostFocus


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Directory List Box Control

Drawing a Control

File List Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 18, "Using the File-System Controls"


File List Box Control

See Also	Properties	Events	Methods

Description

A file list box locates and lists files in the directory specified by the Path property at run time.  You can use this control to display a list of files selected by their file attributes.  This is useful if you want to create dialog boxes in your application that, for example, enable the user to select a file or group of files.

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.  If you also display the directory list box and drive list box controls, you can write code to synchronize them with the file list box and with each other.


Properties

Archive	Height	Parent

BackColor	HelpContextID	Path

DragIcon	Hidden	Pattern

DragMode	hWnd	ReadOnly

Enabled	Index	Selected

FileName	Left	System

FontBold	List	TabIndex

FontItalic	ListCount	TabStop

FontName	ListIndex	Tag

FontSize	MousePointer	Top

FontStrikethru	MultiSelect	TopIndex

FontUnderline	Name	Visible

ForeColor	Normal	Width


Events

Click	KeyDown	MouseMove

DblClick	KeyPress	MouseUp

DragDrop	KeyUp	PathChange

DragOver	LostFocus	PatternChange

GotFocus	MouseDown


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Directory List Box Control

Drawing a Control

Drive List Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 18, "Using the File-System Controls"


Frame Control

See Also	Properties	Events	Methods

Description

A frame provides an identifiable grouping for controls.  You can also use a frame to subdivide a form functionally [image] for example, to separate a group of option buttons from other groups of option buttons.

Remarks

To group controls, first draw the frame and then draw the controls inside the frame.  This enables you to move the frame and controls together.  If you draw a control outside the frame and then try to move it inside, the control will be on top of the frame and you'll have to move the frame and controls separately.

To select multiple controls in a frame, hold down the Ctrl key while using the mouse to draw a box around the controls.


Properties

BackColor	FontSize	MousePointer

Caption	FontStrikethru	Parent

ClipControls	FontUnderline	TabIndex

DragIcon	ForeColor	Tag

DragMode	HelpContextID	Top

Enabled	Height	Visible

FontBold	hWnd	Width

FontItalic	Index

FontName	Left


Events

DragDrop	DragOver


Methods

Drag	Refresh

Move	ZOrder


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Horizontal and Vertical Scroll Bar Controls

See Also	Properties	Events	Methods

Description

Scroll bars provide easy navigation through a long list of items or a large amount of information.  They also can provide an analog representation of current position.  You can use a scroll bar as an input device or indicator of speed or quantity [image] for example, to control the sound volume of a computer game or to view the time elapsed in a timed process.

Remarks

When you're using a scroll bar as an indicator of quantity or speed or as an input device, use the Max and Min properties to set the appropriate range of the control.

To specify the amount of change to report in a scroll bar, use the LargeChange property for clicking in the bar, and the SmallChange property for clicking the arrows at the ends of the bar.  The scroll bar's Value property increases or decreases by the amounts set for the LargeChange and SmallChange properties.  You can position the scroll box at run time by setting Value between 0 and 32,767, inclusive.


Properties

DragIcon	Left	TabStop

DragMode	Max	Tag

Enabled	Min	Top

Height	MousePointer	Value

HelpContextID	Name	Visible

hWnd	Parent	Width

Index	SmallChange

LargeChange	TabIndex


Events

Change	KeyPress

DragDrop	KeyUp

DragOver	LostFocus

GotFocus	Scroll

KeyDown


Methods

Drag	Refresh	ZOrder

Move	SetFocus


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Label Control

See Also	Properties	Events	Methods

Description

A label is a graphical control you can use to display text that the user can't change directly.

Remarks

You can write code that changes a label in response to events at run time.  For example, if your application takes a few minutes to commit a change, you could display a processing-status message in a label.  You can also use a label to identify a control, such as a text box, that does not have its own Caption property.

Set the AutoSize and WordWrap properties if you want the label to properly display variable-length lines or varying numbers of lines.

A label can also act as a destination link in a DDE conversation.  To do this, set the LinkTopic property to establish a link, set the LinkItem property to specify an item for the conversation, and set the LinkMode property to activate the link.  When these have been set, Visual Basic attempts to initiate the conversation and displays a message if it is unable to do so.


Properties

Alignment	FontName	LinkTopic

AutoSize	FontSize	MousePointer

BackColor	FontStrikethru	Name

BackStyle	FontUnderline	TabIndex

BorderStyle	ForeColor	Tag

Caption	Height	Top

DragIcon	Index	Visible

DragMode	Left	Width

Enabled	LinkItem	WordWrap

FontBold	LinkMode

FontItalic	LinkTimeout


Events

Change	DragOver	LinkOpen

Click	LinkClose	MouseDown

DblClick	LinkError	MouseMove

DragDrop	LinkNotify	MouseUp


Methods

Drag	LinkRequest 	ZOrder

LinkExecute 	Move

LinkPoke	Refresh


See Also

Help:

Drawing a Control

TabIndex Property

Text Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


List Box Control

See Also	Properties	Events	Methods

Description

A list box displays a list of items from which the user can select one or more.  If the number of items exceeds what can be displayed, a scroll bar is automatically added to the list box.

Remarks

To add or delete items in a list, use the AddItem or RemoveItem method.  Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.


Properties

BackColor	Height	NewIndex

Columns	HelpContextID	Parent

DragIcon	hWnd	Selected

DragMode	Index	Sorted

Enabled	ItemData	TabIndex

FontBold	Left	TabStop

FontItalic	List	Tag

FontName	ListCount	Text

FontSize	ListIndex	Top

FontStrikethru	MousePointer	TopIndex

FontUnderline	MultiSelect	Visible

ForeColor	Name	Width


Events

Click	GotFocus	LostFocus

DblClick	KeyDown	MouseDown

DragDrop	KeyPress	MouseMove

DragOver	KeyUp	MouseUp


Methods

AddItem	Move	SetFocus

Clear	Refresh	ZOrder

Drag	RemoveItem


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Menu Control

See Also	Properties	Events

Description

A menu control displays a customized menu for your application.  A menu can include commands, submenu titles, and separator bars.  Each menu you create can have up to four levels of submenus.

Remarks

To create a menu control, use the Menu Design window.  Enter the name of the menu in the Caption box.  To create a separator bar, enter a single hyphen (-) in the Caption box.  To display a check mark to the left of a menu item, check the Checked box.

While you can set some menu control properties in the Menu Design window, all menu properties are available in the Properties window.  To display the menu properties, select the menu name in the Objects list at the top of the Properties window.

When you create an MDI (Multiple-Document Interface) application, the menu bar on the MDI child form will replace the menu bar on the MDI form when the child form is active.


Properties

Caption	Index	Tag

Checked	Name	Visible

Enabled	Parent	WindowList

HelpContextID	ShortCut


Events

Click


See Also

Help:

Creating A Menu Bar

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Option Button Control

See Also	Properties	Events	Methods

Description

An option button displays an option that can be turned on or off.

Remarks

Usually, option buttons are used as part of an option group to display multiple choices from which the user can select only one.  You can group option buttons by drawing them inside a frame, a picture box, or directly on a form.  To group option buttons in a frame or picture box, draw the frame or picture box first, and then draw the option buttons inside.  All option buttons within a frame or picture box are treated as a group.  Option buttons on a form are also treated as a separate group from any option buttons in a frame or picture box.

While option buttons and check boxes may appear to function similarly, there is an important difference:  when a user selects an option button, the other option buttons in the same group are automatically cancelled.  In contrast, any number of check boxes can be selected.


Properties

Alignment	FontStrikethru	Parent

BackColor	FontUnderline	TabIndex

Caption	ForeColor	TabStop

DragIcon	Height	Tag

DragMode	HelpContextID	Top

Enabled	hWnd	Value

FontBold	Index	Visible

FontItalic	Left	Width

FontName	MousePointer

FontSize	Name


Events

Click	DragOver	KeyPress

DblClick	GotFocus	KeyUp

DragDrop	KeyDown	LostFocus


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Check Box Control

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Picture Box Control

See Also	Properties	Events	Methods

Description

A picture box can display a graphic from a bitmap, icon, or metafile.  It displays only as much of the graphic as fits into the rectangle that you've drawn with the picture box tool.

Remarks

You can also use a picture box to group option buttons and to display output from graphics methods and text written with the Print method.

To make a picture box automatically resize to display an entire graphic, set its AutoSize property to True.

To create animation or simulation, you can manipulate the graphics properties and methods in your code.  Graphics properties and events are useful for run-time print operations, such as modifying the format of a screen form for printing.

A picture box can also act as a client link in a DDE conversation.

The picture box is the only standard Visual Basic control that you can place in the client area of an MDI form.  You can use it to group controls at the top or bottom of the client area to create a toolbar or status bar.


Properties

Graphics properties are indicated with an asterisk (*).

Align	*FontItalic	LinkTopic

*AutoRedraw	*FontName	MousePointer

AutoSize	*FontSize	Name

BackColor	*FontStrikethru	Parent

BorderStyle	*FontTransparent	Picture

*ClipControls	*FontUnderline	*ScaleHeight

*CurrentX	*ForeColor	*ScaleLeft

*CurrentY	hDC	*ScaleMode

DragIcon	Height	*ScaleTop

DragMode	HelpContextID	*ScaleWidth

*DrawMode	hWnd	TabIndex

*DrawStyle	Image	TabStop

*DrawWidth	Index	Tag

Enabled	Left	Top

*FillColor	LinkItem	Visible

*FillStyle	LinkMode	Width

*FontBold	LinkTimeout


Events

Change	KeyPress	LostFocus

Click	KeyUp	MouseDown

DblClick	LinkClose	MouseMove

DragDrop	LinkError	MouseUp

DragOver	LinkNotify	Paint

GotFocus	LinkOpen	Resize

KeyDown


Methods

Graphics methods are indicated with an asterisk (*).

*Circle	LinkRequest	Refresh

*Cls	LinkSend	*Scale

Drag	Move	SetFocus

*Line	*Point	*TextHeight

LinkExecute	*Print	*TextWidth

LinkPoke	*PSet	ZOrder


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


Text Box Control

See Also	Properties	Events	Methods

Description

A text box control, sometimes called an "edit field" or "edit control," can display information entered at design time, entered by the user, or assigned to the control in code at run time.

Remarks

To display multiple lines of text in a text box, set the MultiLine property to True.  If a multiline text box does not have a horizontal scroll bar, text in the box wraps automatically even when the text box is resized.  To customize the scroll bar combination on a text box, set the ScrollBars property.

A text box can also act as a client link in a DDE conversation.


Properties

Alignment	HelpContextID	PasswordChar

BackColor	HideSelection	ScrollBars

BorderStyle	hWind	SelLength

DragIcon	Index	SelStart

DragMode	Left	SelText

Enabled	LinkItem	TabIndex

FontBold	LinkMode	TabStop

FontItalic	LinkTimeout	Tag

FontName	LinkTopic	Text

FontSize	MaxLength	Top

FontStrikethru	MousePointer	Visible

FontUnderline	MultiLine	Width

ForeColor	Name

Height	Parent


Events

Change	KeyDown	LinkError

DragDrop	KeyPress	LinkOpen

DragOver	KeyUp	LinkNotify

GotFocus	LinkClose	LostFocus


Methods

Drag	LinkRequest 	SetFocus

LinkExecute 	Move	ZOrder

LinkPoke	Refresh


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Timer Control

See Also	Properties	Events

Description

A timer can run code at a regular intervals by causing a Timer event.

Remarks

The timer, invisible to the user, is useful for background processing.

The timer's Enabled property cannot be set for a multiple selection of controls other than timers.


Properties

Enabled	Left	Tag

Index	Name	Top

Interval	Parent


Events

Timer


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Clipboard Object

Methods

Description

The Clipboard object is accessed with the keyword Clipboard, and is used to manipulate text and graphics on the Clipboard.  You can use this object to enable a user to copy, cut, and paste text or graphics in your application.

Remarks

The Clipboard can contain only one set of data.  This data is lost when another set of data is placed on the Clipboard either through code or a menu command.


Methods

Clear	GetFormat	SetData

GetData	GetText	SetText


Debug Object

Methods

Description

The Debug object is accessed with the keyword Debug, and is used to send output to the Debug window at run time.


Method

Print


Printer Object

Properties	Methods

Description

The Printer object is accessed with the keyword Printer.  It is used to control text and graphics printed on a page and to send output directly to the default system printer.  For example, you can use this object to manipulate the appearance of your printed output by changing fonts.

Remarks

You may need to check and revise the layout of your forms if you want to print them.  When you use the Print method, graphical images are clipped at the bottom of the page and text is carried over to the next page.


Properties

CurrentX	FontName	ScaleHeight

CurrentY	Fonts	ScaleLeft

DrawMode	FontSize	ScaleMode

DrawStyle	FontStrikethru	ScaleTop

DrawWidth	FontTransparent	ScaleWidth

FillColor	FontUnderline	TwipsPerPixelX

FillStyle	ForeColor	TwipsPerPixelY

FontBold	hDC	Width

FontCount	Height

FontItalic	Page


Methods

Circle	NewPage	Scale

EndDoc	Print	TextHeight

Line	PSet	TextWidth


Screen Object

Properties

Description

The Screen object is accessed with the keyword Screen, and is used to manipulate forms according to their placement on the screen and to control the mouse pointer outside of your application's forms at run time.  For example, you could set the MousePointer property for the Screen object to the hourglass pointer while a modal form is displayed.


Properties

ActiveControl	Fonts	TwipsPerPixelX

ActiveForm	Height	TwipsPerPixelY

FontCount	MousePointer	Width


App Object

See Also	Properties

Description

The App object is a global object accessed with the App keyword.  It determines or specifies information about the application's title, the path and name of its executable and Help files, and whether or not there is a previous instance of the application running.

Remarks

The App object has no events or methods.


Properties

EXEName	PrevInstance

HelpFile	Title

Path


See Also

Help:

HelpContextID Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Image Control

See Also	Properties	Events

Description

Image is a graphical control that you can use to display a picture.

Remarks

The image control uses fewer resources and repaints faster than a picture box control, but it supports only a subset of the picture box properties, events, and methods.  Use the Stretch property to determine whether the picture is scaled to fit the control or vice versa.  Note that although you can place an image control within a container, an image control cannot act as a container.


Properties

BorderStyle	Left	Tag

DragIcon	MousePointer	Top

DragMode	Name	Visible

Enabled	Parent	Width

Height	Picture

Index	Stretch


Events

Click	MouseDown

DblClick	MouseMove

DragDrop	MouseUp

DragOver


Methods

Drag	Refresh

Move	ZOrder


See Also

Help

Drawing a Control

Picture Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Line Control

See Also	Properties	Methods

Description

Line is a graphical control displayed as a horizontal, vertical, or diagonal line.

Remarks

You can use a line control at design time to draw lines on forms.  At run time, you can use a line control instead of, or in addition to, the Line method.  Lines drawn with the line control will remain on the form even if the AutoRedraw property is False.  Line controls can be displayed on forms, in picture boxes, and in frames.  You cannot use the Move method to move a line control at run time but you can move or resize it by altering its X1, X2, Y1, Y2 properties.  Note that the effect of setting the BorderStyle property depends on the setting of the Borderwidth property.  If BorderWidth is not 1 and BorderStyle is not 0 or 6, BorderStyle is set to 1.


Properties

BorderColor	Name

BorderStyle	Parent

BorderWidth	Tag

DrawMode	Visible

Index	X1, X2, Y1, Y2


Methods

Refresh

ZOrder


See Also

Help:

Drawing a Control

Frame Control

Line Method

Picture Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


Shape Control

See Also	Properties	Methods

Description

Shape is a graphical control displayed as a rectangle, square, oval, circle, rounded rectangle, or rounded square.

Remarks

Use shape controls at design time instead of, or in addition to, invoking Circle and Line methods at run time.  You can draw a shape control in a container but it cannot act as a container.  Note that the effect of setting the BorderStyle property depends on the setting of the Borderwidth property.  If BorderWidth is not 1 and BorderStyle is not 0 or 6, BorderStyle is set to 1.


Properties

BackColor	FillColor	Parent

BackStyle	FillStyle	Shape

BorderColor	Height	Tag

BorderStyle	Index	Top

BorderWidth	Left	Visible

DrawMode	Name	Width


Methods

Move

Refresh

ZOrder


See Also

Help:

Circle Method

Drawing a Control

Frame Control

Line Method

Picture Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


MDI Form

See Also	Properties	Events	Methods

Description

An MDI (Multiple-Document Interface) form is a window that acts as the background of an application and is the container for forms that have their MDIChild property set to True.

Remarks

You create an MDI form by choosing New MDI Form from the File menu.

An application can have only one MDI form but many MDI child forms.  If an MDI child form has menus, the child form's menu bar automatically replaces the MDI form's menu bar when the child form is active.  A minimized MDI child form appears as an icon within the MDI form.

MDI forms can contain only menu and picture box controls and custom controls that have an Align property.  To place other controls on an MDI form, you can draw a picture box on the form and then draw other controls inside the picture box.  You can use the Print method to display text in a picture box on an MDI form, but you can't use this method to display text on the MDI form itself.

An MDI form cannot be modal.

Note that MDI child forms are designed independently of the MDI form, but are always contained within the MDI form at run time.


Properties

ActiveForm	Icon	ScaleWidth

ActiveControl	Left	ScrollBars

Caption	LinkMode	Tag

Enabled	LinkTopic	Top

Height	MousePointer	Visible

HelpContextID	Name	Width

hWnd	ScaleHeight	WindowState


Events

Activate	LinkClose	Load

Deactivate	LinkError	QueryUnload

DragDrop	LinkExecute	Resize

DragOver	LinkOpen	Unload


Methods

Arrange	SetFocus

Hide	Show

Move	ZOrder


See Also

Help:

Creating a Menu Bar

Creating an MDI Application

Forms Collection

Specifying a Startup Form

Using DDE

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 8, "Objects and Instances"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Forms Collection

See Also	Properties	Example

Description

A collection whose elements represent each loaded form in an application.  The collection includes the application's MDI form, MDI child forms, and non-MDI forms.  The Forms collection has a single property, Count, that specifies the number of elements in the collection.

Usage

Forms(index)[.control][.property][ = setting ]

Remarks

In the preceding syntax, the range of index is 0 to Forms.Count-1.  The Forms collection is useful for iterating through all loaded forms in an application.  Note that Forms is a keyword, but not a reserved word.  It identifies an intrinsic global variable named Forms.  You can use Forms(index) as an argument to a function with a parameter of type Form.


Properties

Count


See Also

Help:

Controls Collection

Dim Statement

Programmer's Guide:

Chapter 8, "Objects and Instances"


Forms Collection Example

The OBJECTS.MAK file referred to in Chapter 8 of the Programmer's Guide includes the following procedure to fill a listbox with the captions of all the currently loaded forms:

Sub Form_Activate ()

Dim I	' Declare variable.

' Refill list (in case an instance was added or removed).

lstForms.Clear	' Clear listbox.

For I = 0 To Forms.Count - 1

lstForms.AddItem Forms(I).Caption

Next I

End Sub


Controls Collection

See Also	Properties	Example

Description

A collection whose elements represent each control on a form, including elements of control arrays.  The Controls collection has a single property, Count, that specifies the number of elements in an array.

Usage

[form.]Controls(index)[.property][ = setting ]

form(index)[.property][ = setting ]

Remarks

The Controls collection enumerates loaded controls on a form and is useful for iterating through them.  The index in the syntax is between 0 and Controls.Count-1.  Note that Controls is a keyword but not a reserved word.  It identifies an intrinsic form-level variable named Controls.  If you omit the optional form reference, you must include the Controls keyword.  If you include a form reference, you can omit the Controls keyword.  For example, the following two lines have the same effect:

MyForm.Controls(6).Top = MyForm.Controls(5).Top + increment

MyForm(6).Top = MyForm(5).Top + increment

You can use Controls(index) as an argument to a function with a parameter of type Control.


Properties

Count


See Also

Help:

Forms Collection

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 8, "Objects and Instances"


Controls Collection Example

The OBJECTS.MAK file referred to in Chapter 8 of the Programmer's Guide includes the following procedure to enable all currently loaded controls on a form (except menus).

Sub EnableControlsOn (Frm As Form, State As Integer)

Dim I	' Declare variable.

For I = 0 To Frm.Controls.Count - 1

If TypeOf Frm.Controls(I) Is Not Menu Then

Frm.Controls(I).Enabled = State

End If

Next I

End Sub


Graphical Controls

See Also

Description

The graphical controls [image] image, label, line and shape [image] can improve the performance of your application by using fewer system resources than other controls.

Remarks

The graphical controls can't receive the focus or act as containers for other controls, and they have no hWnd property.  The graphical controls generally have fewer properties, recognize fewer events, and have fewer methods than other controls.  For example, an image control can display a picture but can't be the object of a graphics method (such as the Print, Line and Circle methods) as a picture box control can.

Graphical controls can be transparent.  For example, if you set label.Backstyle = 0 or shape.BackStyle = 0, objects that these controls are covering will become visible.  You can use the line and shape controls to draw lines and shapes at design time instead of using the Line and Circle methods at run time.


See Also

Help:

Image Control

Label Control

Line Control

Shape Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


Grid Control

See Also	Properties	Events	Methods

Description

A grid control displays a series of rows and columns.  The intersection of a row and column is a cell.  You can read and set the contents of each cell programmatically.

Remarks

You can put either text or a picture in any cell of a grid.

The Row and Col properties specify the current cell in a grid.  You can specify the current cell in code, or the user can change it at run time using the mouse or the arrow keys.  The Text property references the contents of the current cell.

If a cell's text is too long to be displayed in the cell, the text wraps to the next line within the same cell.  To display the wrapped text, you must increase the cell's column width (ColWidth property) or row height (RowHeight property).

When a new element of a control array is loaded at run time, the new element does not inherit the original control's run-time properties.

Note	Before you can use a grid control in your application, you must add GRID.VBX to your project using the Add File command on the File menu.  To automatically include GRID.VBX in new projects, put it in an AUTOLOAD.MAK file.  When distributing your application, you should install the GRID.VBX file in the user's Microsoft Windows \SYSTEM subdirectory.


See Also

Programmer's Guide:

Chapter 8, "Objects and Instances"


Properties

BackColor	FontName	RowHeight
BorderStyle	FontSize	Rows
CellSelected	FontStrikethru	ScrollBars
Clip	FontUnderline	SelEndCol
Col	ForeColor	SelEndRow
ColAlignment	GridLines	SelStartCol
Cols	Height	SelStartRow
ColWidth	HelpContextID	TabIndex
DragIcon	HighLight	TabStop
DragMode	hWnd	Tag
Enabled	Index	Text
FillStyle	Left	Top
FixedAlignment	LeftCol	TopRow
FixedCols	Name	Visible
FixedRows	Parent	Width
FontBold	Picture
FontItalic	Row


Events

Click	KeyDown	MouseMove
DblClick	KeyPress	MouseUp
DragDrop	KeyUp	RowColChange
DragOver	LostFocus	SelChange
GotFocus	MouseDown


Methods

AddItem	RemoveItem
Drag	SetFocus
Move	ZOrder
Refresh


CellSelected Property

See Also	Example

Applies To

Grid.

Description

Determines whether the cell specified by the Col and Row properties (the active cell) is within the grid's selected region.  Not available at design time; read-only at run time.

Usage

[form.]grid.CellSelected

Setting

The CellSelected property settings are:

Setting 	Description

True 	The specified cell is within the selected area.

False	The specified cell is not within the selected area.

Remarks

This property allows you to determine whether the user has selected a specific cell or a specific range of cells.

At run time, the user can select a range of cells by clicking a cell and then dragging the mouse or by pressing the Shift key and using the arrow keys.

Use the SelEndCol, SelStartCol, SelEndRow, SelStartRow properties to determine the selected region.  Use the Col and Row properties to determine the active cell.

Data Type

Integer (Boolean)


See Also

Help:

Col, Row Properties

RowColChange Event

SelChange Event

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


CellSelected Example

The example selects a cell at random and tells you whether it is selected or not when the grid is clicked.  To try this example, use the Add File command on the File menu to add GRID.VBX to the project, paste the code into the Declarations section of a new form, and then draw a grid and a label.  For the label, set AutoSize to True.  Press F5 to run the program.

Dim TRow As Integer

Dim TCol As Integer

Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

Randomize

' Choose a cell at random.

TRow = Int(Rnd * (Grid1.Rows - 1)) + 1

TCol = Int(Rnd * (Grid1.Cols - 1)) + 1

End Sub

Sub Grid1_Click ()

Grid1.Row = TRow

Grid1.Col = TCol

If Grid1.CellSelected Then

Label1.Caption = "You found it!"

Else

Label1.Caption = "Not yet. Try again."

End If

End Sub


Clip Property

See Also	Example

Applies To

Grid.

Description

Determines the contents of the cells in a grid's selected region.  Not available at design time.

Usage

[form.]grid.Clip[ = stringexpression ]

Remarks

The stringexpression can contain the contents of multiple rows and columns.  In stringexpression, a tab character (ANSI character 9) indicates a new cell in a row, and a carriage return (ANSI character 13) indicates the beginning of a new row.  Use the Chr function to embed these characters in strings.  For example, this line of code puts text into a selected area two rows high and two columns wide:

Grid1.Clip = "1st" & Chr(9) & "a" & Chr(13) & "2nd" & Chr(9) & "b"

When placing data into a grid, only the selected cells are affected. If there are more cells in the selected region than are described in stringexpression, the remaining cells are set to null. If there are more cells described in stringexpression than in the selected region, the unused portion of stringexpression is ignored.

Data Type

String


See Also

Help:

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Clip Property Example

The example puts the current date and time into the selected area of the grid when the user clicks the form.  To try this example, use the Add File command on the File menu to add GRID.VBX to a project, paste the code into the Declarations section of a new form, and then draw a grid.  Press F5 to run the program.

Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

End Sub

Sub Form_Click ()

Dim Msg As String

Msg = "Date" & Chr(9)	' Create a text string.

Msg = Msg & Format(Now, "Short Date") & Chr(13)

Msg = Msg & "Time" & Chr(9)

Msg = Msg & Format(Now, "Short Time")

Grid1.Clip = Msg	' Paste string into grid.

End Sub


Col, Row Properties

See Also	Example1	Example2

Apply To

Grid.

Description

Determine the active cell in a grid.  Not available at design time.

Usage

[form.]grid.Col[ = column ]

[form.]grid.Row[ = column ]

Remarks

Use these properties to specify a cell in a grid or to find out which row or column contains the active cell in a selected region.  Columns and rows are numbered from zero, beginning at the top for rows and at the left for columns.  Setting these properties at run time does not change which cells are selected.  Use SelEndCol, SelStartCol, SelEndRow, SelStartRow properties to specify a selected region.

Note	The Col, Row properties are not the same as the Cols, Rows properties.

Data Type

Integer


See Also

Help:

Clip Property

Cols, Rows Properties

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Col, Row Properties Example

The example puts "Here" into the current cell, and then changes the active cell to the third cell in the third row and puts "There" into that cell.  To try this example, use the Add File command on the File menu to add GRID.VBX to the project, and then draw a grid on a new form.  To run the program, press F5 and then click the grid.

Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

End Sub

Sub Grid1_Click ()

' Put text in current cell.

Grid1.Text = "Here"

' Put text in 3rd row, 3rd column.

Grid1.Col = 2

Grid1.Row = 2

Grid1.Text = "There"

End Sub


ColAlignment Property

See Also	Example

Applies To

Grid.

Description

Determines the alignment of data in a column.  Not available at design time.

Usage

[form.]grid.ColAlignment(column)[ = numericexpression ]

Setting

The ColAlignment property settings are:

Setting 	Description

0 	(Default) Left align

1	Right align

2	Center

Remarks

Any column can have an alignment that is different from other columns.  This property does not affect cells in a fixed row.  To set the alignment for a fixed column, use the FixedAlignment property.

Data Type

Integer (Enumerated)


See Also

Help:

Alignment Property

FixedAlignment Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ColAlignment Property Example

The example fills a grid with the letter "m" and then sets the column alignment to right-aligned for every other column.  To try this example, use the Add File command on the File menu to add GRID.VBX to the project, and then draw a grid on a new form.  To run the program, press F5.

Sub Form_Load ()

Grid1.Cols = 5	' Set Cols and Rows.

Grid1.Rows = 8

' Select all cells

Grid1.SelStartCol = 1

Grid1.SelStartRow = 1

Grid1.SelEndCol = Grid1.Cols - 1

Grid1.SelEndRow = Grid1.Rows - 1

' Fill all cells with a letter

Grid1.FillStyle = 1	' Turn on FillStyle.

Grid1.Text = "m"

' Set ColAlignment for even numbered columns

For I = 2 To 4 Step 2

Grid1.ColAlignment(I) = 1	' Right align.

Next I

Grid1.FillStyle = 0	' Turn off FillStyle.

End Sub


Cols, Rows Properties

See Also	Example

Apply To

Grid.

Description

Determine the total number of columns or rows in a grid.  The minimum is 1.  The maximum number of rows is 2000; the maximum number of columns is 400.

Usage

[form.]grid.Cols[ = numericexpression ]

[form.]grid.Rows[ = numericexpression ]

Remarks

You can use these properties to expand a grid dynamically at run time.  A grid must have at least one non-fixed column and one non-fixed row.

Note	The Cols, Rows properties are not the same as the Col, Row properties.

Data Type

Integer


See Also

Help:

Col, Row Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ColWidth Property

See Also	Example

Applies To

Grid.

Description

Determines the width of the specified column in twips.  Not available at design time.

Usage

[form.]grid.ColWidth(column)[ = numericexpression ]

Remarks

You can use this property to set the width of any column at run time.  Users can also change the width of a column by positioning the mouse pointer between columns and then clicking and dragging.

Data Type

Long


See Also

Help:

RowHeight Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ColWidth Property Example

The example allows the user to increase the column width of selected columns with the > key, and decrease the column width with the < key.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 8

End Sub

Sub Grid1_KeyPress (KeyAscii As Integer)
Select Case KeyAscii
Case 62	' > key
' Get index for each selected column.
For I = Grid1.SelStartCol To Grid1.SelEndCol
' Increase column width.
Grid1.ColWidth(I) = Grid1.ColWidth(I) + 50
Next I
Case 60	' < key
'Get index for each selected column.
For I = Grid1.SelStartCol To Grid1.SelEndCol
'Decrease column width.
Grid1.ColWidth(I) = Grid1.ColWidth(I) - 50
Next I
End Select
End Sub


FixedAlignment Property

See Also	Example

Applies To

Grid.

Description

Determines the alignment of data in the fixed cells of a column.  Not available at design time.

Usage

[form.]grid.FixedAlignment(column)[ = numericexpression ]

Setting

The FixedAlignment property settings are:

Setting 	Description

0 	(Default) Left align.

1	Right align.

2	Center.

3	Use the ColAlignment setting for the column specified by the column index.

Remarks

This property operates like the ColAlignment property except that it only affects the alignment of fixed cells.  This is useful when you want to align headings differently from the rest of the columns.

Data Type

Integer (Enumerated)


See Also

Help:

ColAlignment Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


FixedAlignment Example

The example creates a spreadsheet with centered column headings and row numbers.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 5	' Set rows and columns.

Grid1.Rows = 7

Grid1.Row = 0

Grid1.FixedAlignment(0) = 2	' Set alignment of row numbers.

For I = 1 To Grid1.Cols - 1	' Set column letters & alignment.

Grid1.FixedAlignment(I) = 2

Grid1.Col = I

Grid1.Text = Chr(64 + I)

Next I

Grid1.Col = 0

For I = 1 To Grid1.Rows - 1	' Set row numbers.

Grid1.Row = I

Grid1.Text = I

Next I

End Sub


FixedCols, FixedRows Properties

See Also	Example

Apply To

Grid.

Description

Determine the total number of fixed columns or fixed rows for a grid.  By default, a grid has one fixed column and one fixed row.

Usage

[form.]grid.FixedCols[ = numericexpression ]

[form.]grid.FixedRows[ = numericexpression ]

Remarks

A fixed column is a stationary column on the left side of the grid. A fixed row is a stationary row along the top of the grid. You can have zero or more fixed columns and zero or more fixed rows.  Fixed columns and rows are displayed in gray and do not move when the other columns or rows in the grid are scrolled. You cannot change the color of a fixed column or row.

Fixed columns and rows are typically used in spreadsheet applications to display row numbers and column names or letters.

A grid must have at least one non-fixed column and one non-fixed row.  The maximum number of fixed columns or rows allowed in a grid is one less than the total number of columns or rows.

Data Type

Integer


See Also

Help:

Cols, Rows Properties

FixedAlignment Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


FixedCols, FixedRows Properties Example

The example illustrates a grid with two fixed rows and two fixed columns.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  To run the program, press F5.

Sub Form_Load ()

Grid1.Rows = 8	' Set columns and rows.

Grid1.Cols = 6

Grid1.FixedRows = 2	' Set fixed columns and rows.

Grid1.FixedCols = 2

End Sub


GridLines Property

See Also	Example

Applies To

Grid.

Description

Determines whether the lines between cells are visible.

Usage

[form.]grid.Gridlines[ = {True|False}]

Setting

The GridLines property settings are:

Setting 	Description

True 	(Default) Grid lines are visible.

False	Grid lines are not visible.

Data Type

Integer (Boolean)


See Also

Help:

Cols, Rows Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


GridLines Property Example

The example turns the gridlines on and off as you click the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Sub Form_Click ()	' Toggle gridlines on and off.

Grid1.GridLines = Not Grid1.GridLines

End Sub


HighLight Property

See Also	Example

Applies To

Grid.

Description

Determines whether selected cells appear highlighted.

Usage

[form.]grid.Highlight[ = {True|False}]

Setting

The HighLight property settings are:

Setting 	Description

True 	(Default) Selected cells are highlighted.

False	Selected cells are not highlighted.

Remarks

When this property is set to False and the user selects a range of cells, there is no visual cue that shows which cells are currently selected.

Data Type

Integer (Boolean)


See Also

Help:

Col, Row Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


HighLight Property Example

The example turns the highlighting on and off as you click the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Sub Form_Click ()	' Toggle highlighting on and off.

Grid1.HighLight = Not Grid1.HighLight

End Sub


LeftCol Property

See Also	Example

Applies To

Grid.

Description

Determines the leftmost visible column (other than a fixed column) in the grid.  Not available at design time.

Usage

[form.]grid.LeftCol[ = numericexpression ]

Remarks

You can use this property in code to scroll a grid programmatically.  Use the TopRow property to determine the topmost visible row in the grid.

Data Type

Integer


See Also

Help:

Col, Row Properties

TopRow Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


LeftCol Property Example

The example changes the LeftCol property with each click of the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Rows = 8	' Set columns and rows.

Grid1.Cols = 9

Grid1.Row = 0

For I = 1 To Grid1.Cols - 1	' Set numbers in column heads.

Grid1.Col = I

Grid1.Text = I

Next I

End Sub

Sub Form_Click ()

On Error GoTo LeftColError

' Scroll the grid by one column.

Grid1.LeftCol = Grid1.LeftCol + 1

On Error GoTo 0

Exit Sub

LeftColError:

Grid1.LeftCol = 1	' Display the first column.

Resume Next

End Sub


RowHeight Property

See Also	Example

Applies To

Grid.

Description

Determines the height of the specified row in twips.  Not available at design time.

Usage

[form.]grid.RowHeight(rownum)[ = numericexpression ]

Remarks

The minimum RowHeight is 1 pixel.  Users can change the RowHeight of any row at run time by placing the mouse pointer on a gridline between rows and then clicking and dragging.

Data Type

Long


See Also

Help:

ColWidth Property

Row Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


RowHeight Property Example

The example sets the height of the current row to 500 twips when you click the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section, press F5 to run the program, and then select a cell and click the form.

Sub Form_Load ()

Grid1.Rows = 5	' Set columns and rows.

Grid1.Cols = 7

End Sub

Sub Form_Click ()
Grid1.RowHeight(Grid1.Row) = 500
End Sub


SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

See Also	Example

Apply To

Grid.

Description

Determine the starting or ending row or column for a range of cells.  Not available at design time.

SelEndCol [image] the last selected column on the right.

SelStartCol [image] the first selected column on the left.

SelEndRow [image] the lowest selected row.

SelStartRow [image] the first selected row.

Usage

[form.]grid.SelEndCol[ = numericexpression ]

[form.]grid.SelStartCol[ = numericexpression ]

[form.]grid.SelEndRow[ = numericexpression ]

[form.]grid.SelStartRow[ = numericexpression ]

Remarks

You can use these properties to select a specific region of the grid from code, or to read into code the dimensions of an area that the user selects.

SelStartCol and SelStartRow together specify the cell in the upper-left corner of a selected range.  SelEndCol and SelEndRow specify the cell in the lower-right corner of a selected range.

To specify a cell without moving the current selection, use the Col and Row properties.

Data Type

Integer


See Also

Help:

Col, Row Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TopRow Property

See Also	Example

Applies To

Grid.

Description

Determines the uppermost row displayed in the grid.  Not available at design time.

Usage

[form.]grid.TopRow[ = numericexpression ]

Remarks

You can use this property in code to programmatically read or set the visible top row of the grid.  Use the LeftCol property to determine the leftmost visible column in the grid.

When setting this property, the largest possible row number is the total number of rows minus the number of rows that can be visible in the grid.  Attempting to set TopRow to a greater row number will generate an error.

Data Type

Integer


See Also

Help:

Col, Row Properties

LeftCol Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TopRow Property Example

The example changes the TopRow property with each click on the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

' Set columns and rows.

Grid1.Cols = 6

Grid1.Rows = 12

' Put numbers in row heads.

Grid1.Col = 0

For I = 1 To Grid1.Rows - 1

Grid1.Row = I

Grid1.Text = I

Next I

End Sub

Sub Form_Click ()

On Error GoTo TopRowError

Grid1.TopRow = Grid1.TopRow + 1

On Error GoTo 0

Exit Sub

TopRowError:

Grid1.TopRow = 1

Resume Next

End Sub


SelChange Event

See Also	Example

Applies To

Grid.

Description

Occurs when the selected range changes to a different cell or range of cells.

Syntax

Sub grid_SelChange ( )

Remarks

The SelChange event occurs whenever the user clicks a cell other than the selected cell and as a user drags to select a new range of cells.  A user can also select a range of cells by pressing the Shift key and using the arrow keys.

You can trigger this event in code by changing the selected region using the SelEndCol, SelStartCol, SelEndRow, SelStartRow properties.

The RowColChange event also occurs when a user clicks a new cell but does not occur while a user drags the selection across the grid, or when you programmatically change the selection without moving the active cell.


See Also

Help:

RowColChange Event

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


RowColChange Event

See Also	Example

Applies To

Grid.

Description

Occurs when the currently active cell changes to a different cell.

Syntax

Sub grid_RowColChange ( )

Remarks

This event occurs whenever the user clicks a cell other than the selected cell or when you programmatically change the active cell within a selection.

You can trigger this event in code by changing the current cell using the Col and Row properties.

The SelChange event also occurs when a user clicks a new cell, but does not occur when you programmatically change the selected range without changing the active cell.


See Also

Help:

SelChange Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


RowColChange, SelChange Events Example
Col, Row; Cols, Rows; SelEndCol, SelEndRow, SelStartCol, SelStartRow Properties Example

The example displays the location of the active cell and the range of the selection as a user selects cells or ranges.  Notice that when selecting a range, the active cell does not change.  Select a range and then click the form to move the active cell around the perimeter of the selection.  Notice that the selected range does not change.

To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid and two labels.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Sub Grid1_RowColChange ()

Msg = "Active Cell: " & Chr(64 + Grid1.Col)

Mst = Msg & Grid1.Row

Label1.Caption = Msg

End Sub

Sub Grid1_SelChange ()

Msg = "Selection: " & Chr(64 + Grid1.SelStartCol)

Msg = Msg & Grid1.SelStartRow

Msg = Msg & ":" & Chr(64 + Grid1.SelEndCol)

Msg = Msg & Grid1.SelEndRow

Label2.Caption = Msg

End Sub

Sub Form_Click ()

' This procedure moves the active cell around

' the perimeter of the current selected range

' of cells with each click on the form.

Dim GR, GC As Integer

If Grid1.Row = Grid1.SelStartRow Then

If Grid1.Col = Grid1.SelEndCol Then

GR = 1: GC = 0

Else

GR = 0: GC = 1

End If

ElseIf Grid1.Row = Grid1.SelEndRow Then

If Grid1.Col = Grid1.SelStartCol Then

GR = -1: GC = 0

Else

GR = 0: GC = -1

End If

Else

If Grid1.Col = Grid1.SelStartCol Then

GR = -1: GC = 0

Else

GR = 1: GC = 0

End If

End If

Grid1.Row = Grid1.Row + GR

Grid1.Col = Grid1.Col + GC

End Sub


Cannot remove last non-fixed row

A grid must contain at least one row.


Cannot use AddItem on a fixed row

You cannot insert a fixed row in a grid. Use the FixedRows property to set the number of fixed rows in a grid.


Cannot use RemoveItem on a fixed row

You cannot delete a fixed row from a grid.  The number of fixed rows in a grid is determined by the FixedRows property.


Cols must be one more than FixedCols value

There must be at least one non-fixed row and one non-fixed column.  FixedCols or FixedRows cannot be equal or greater than Cols or Rows, respectively.


FixedCols must be one less than Cols value

The number of columns assigned as Fixed in a grid must be one less than the number of columns.


FixedRows must be one less than Rows value

The number of Rows assigned as fixed in a grid must be one less than the number of rows.


Grid does not contain that row

You have tried to access a row that does not exist. The first row in a grid is zero. Therefore, the last row in a grid is the number of rows minus one. Use the Rows property to set or return the number of rows in a grid.


Invalid alignment value

The valid values for the ColAlignment and FixedAlignment properties are 0 [image] Left Justify, 1 [image] Right Justify, and 2 [image] center. FixedAlignment has an additional setting: 3 [image] Use ColAlignment Value.


Invalid column number for alignment

You cannot align a fixed column with ColAlignment; use the FixedAlignment property. Set the index argument of the ColAlignment property to a column that is not a fixed column. The FixedCols property returns the number of fixed columns in a grid.


Invalid column value

You have attempted to access a column that does not exist. The first column in a grid is zero. Therefore, the last column in a grid is the number of columns minus one. Use the Cols property to set or return the number of columns in a grid.


Invalid column width value

ColWidth must be greater than or equal to one.


Invalid row height value

RowHeight must be greater than or equal to one.


Invalid row value

You have attempted to access a row that does not exist. The first row in a grid is zero. Therefore, the last row in a grid is the number of rows minus one. Use the Rows property to set or return the number of rows in a grid.


Not a valid picture type

You cannot display a Windows metafile (.WMF) in a grid cell. The Picture property supports only bitmaps (.BMP) and icons (.ICO).


Rows must be one more than FixedRows value

The number of Rows assigned in a grid must be one more than the number of fixed rows.


Unable to allocate memory for grid

You are getting low on memory.  Close some unused applications or documents.


Unable to register the memory manager

There was insufficient memory to store the requested information in the grid.


'|' Dynaset method illegal - no scrollable cursor support
<method>: Dynaset method illegal - no scrollable cursor support

A Move method (other than MoveNext) was attempted.  ODBC Level 1 database drivers do not support these methods.  In order to move to a prior position in a Dynaset (e.g., MovePrevious), close the Dynaset and reopen it.  Then issue MoveNext methods until the record is found.


Access attempted on unopened database

An attempt was made to perform an operation on a database object which is not open.  Issue an OpenDatabase call prior to performing any operations.


Access attempted on unopened Dynaset

An operation was requested on a closed Dynaset object. Open the Dynaset and retry the operation.


Property value only valid when Field is part of a Dynaset

An attempt  was made to set or get the Value property of a Field object (either directly or via GetChunk/AppendChunk methods) when the Field object is not attached to a Dyanset object.


Append illegal - Index is part of a TableDefs collection

An Index object was specified as an argument to an Indexes.Append operation when it already is a member of an existing Indexes collection. Dim a new Index object, specify its values, and retry the operation with the new Index object.


Attempt to Move past EOF

A MoveNext method was specified on a Dynaset after EOF was encountered.


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

An attempt was made to change the value of a property of an object (TableDef, Field, etc.) that is a part of an open Database object.


CommitTrans/Rollback illegal - Transactions not supported

The database or its driver does not support transactions.


Data type of field '|' not supported by target database
Data type of field '<field name>' not supported by target database

The named field's type is not supported by the database to which you have connected.  Substitute a different type for this field if possible.


Delete method requires a name argument

A collection's Delete method requires a name.  Add the name argument and reissue the request.


Dynaset is not updatable or Edit method has not been invoked

The Update method was requested on a Dynaset when either the user had not previously specified the Edit method or the Dynaset was not updatable.  For the latter, check the Dynaset's Updatable property prior to attempting updates.


Field size illegal for specified field type

Field.Size is illegal for the given field type. Reset the property to a legal value.


Field type is illegal

Field.Type specified is illegal.  Reset the property to a legal value.


General ODBC error: '|'
General ODBC error: '<error>'

ODBC or the Database reported an error in the operation.  The specific error information is contained in the variable portion of this message.


Get value not allowed on collections

An attempt was made to get the value of a member of a collection.


GetChunk: Offset/Size argument combination illegal

Either the Size argument was greater than 64K or the Offset is illegal.  GetChunk methods must progress through the field without backtracking or skipping data. Reissue the method with the arguments corrected.


Name not found in this collection

A column was specified that could not be found in the Collection object.  Correct the column name or the collection.


No fields defined - cannot append table

An attempt was made to append a Table object that has no fields defined.  Append one or more fields to the Table object's fields collection and reissue the request.


ODBC - GetDriverFunctions failure

Unable to determine functions for this database driver. This error may occur if the ODBC database driver does not conform to ODBC level 1 requirements.


ODBC - SQLAllocConnect failure

Unable to allocate an ODBC Connection handle.  This error may occur if there is insufficient memory to process the request.


ODBC - SQLAllocStmt failure

Unable to allocate an ODBC Statement handle.  This error may occur if there is insufficient memory to process the request.


ODBC - SQLAllocEnv failure

Unable to allocate an ODBC Environment handle.  This error may occur if there is insufficient memory to process the request.


ODBC - SQLBindCol failure

Unable to bind column information to memory.  This error may occur if the ODBC database driver does not conform to ODBC level 1 requirements.


ODBC - SQLColumns (Fields.Refresh) failure: '|'
ODBC - SQLColumns (Fields.Refresh) failure: '<error>'

Unable to determine the fields in a table.  Specific error information is contained in the variable portion of the message.


ODBC - SQLConfigDataSource error '|'
ODBC - SQLConfigDataSource error '<error>'

RegisterDatabase failed. The exact error text is included in the variable portion of this message.


ODBC - SQLConnect failure '|'
ODBC - SQLConnect failure '<error>'

ODBC Connection to the Database failed.  The specific error information is contained in the variable portion of this message.


ODBC - SQLFetch failure: '|'
ODBC - SQLFetch failure: '<error>'

Unable to request data from the database. Specific error information is contained in the variable portion of this message.


ODBC - SQLFreeConnect error

Unable to free a connection handle.


ODBC - SQLStatistics (Indexes.Refresh) failure: '|'
ODBC - SQLStatistics (Indexes.Refresh) failure: '<error>'

Unable to determine the indexes for a table.  Specific error information is contained in the variable portion of the message.  This could also occur if there are transactions pending in a SQL Server database. Commit or rollback transactions and reissue the request.


ODBC - SQLTables (TableDefs.Refresh) failure: '|'
ODBC - SQLTables (TableDefs.Refresh) failure: '<error>'

Unable to determine the tables in a database.  May occur if the ODBC database driver does not conform to ODBC level 1 requirements.


ODBC driver does not support exclusive access to Dynasets

CreateDynaset methods Exclusive argument is set to TRUE.  Set this to FALSE and reissue the method.


ODBC objects require VBODBCA.DLL

Could not locate the VBODBCA.DLL file. Check setup or the location of the VBODBCA.DLL file.


OpenDatabase - invalid connect string

The connection string supplied in this call was invalid.  Correct the string and reissue the request.


Property is read-only

An attempt was made to set the value of a read-only property.


Property not found

Attempt to access a reserved or unknown property for the object specified.  Correct the property name and retry the request.


Reserved parameter must be FALSE

The Exclusive argument of the OpenDatabase call must be set to FALSE.  Reissue the call with the correct argument.


Row-returning SQL is illegal in ExecuteSQL method

Not allowed to issue row-returning SQL as an argument to this method.  Use the CreateDynaset method for row-returning operations.


Set field value illegal without previous Edit or AddNew method

Attempt to change the Value property of a Field without issuing Edit/AddNew.  Issue the appropriate Edit/AddNew and retry the operation.


Set value not allowed on collections

Attempt to set the value of a property or member of a collection.


Table exists - append not allowed

Append method's argument specified a table which already exists in the database. Change the table's name property and reissue the request.


Unable to build data type table

Failure to determine/create the data type table for the OpenDatabase request.  May occur if the ODBC database driver is not Level 1-compliant or if there is insufficient memory to complete the process.


Update illegal without previous Edit or AddNew method

An Update method was issued with no prior Edit or AddNew method.  Issue the appropriate method and retry the request.


Warning: | (ODBC - SQLSetConnectOption failure)
Warning: <operation> (ODBC - SQLSetConnectOption failure)

The variable portion of this message identifies the operation requested. A failure is most likely due to a non-Level 1-compliant ODBC driver.


Zero rows affected by Update method

An Update method resulted in no rows being affected in the base table to which the Dynaset refers.


| illegal - no current record
'<item>' illegal - no current record

Edit or Delete method attempted when no current record is available.  Most likely cause is being at EOF or attempting access on an empty Dynaset.  Check Dynaset's EOF property prior to requesting Edit or Delete method.


ODBC - SQLNumResultCols (Create Dynaset) failure: '|'
ODBC - SQLNumResultCols (Create Dynaset) failure: '<error>'

Unable to determine the number of columns in a dynaset.


ODBC - SQLDescribeCol (Create Dynaset) failure '|'
ODBC - SQLDescribeCol (Create Dynaset) failure '<error>'

Unable to determine the nature of the columns in a dynaset


Append illegal - field is part of a TableDefs collection

A Field object was specified as an argument to a Fields.Append operation when it already is a member of an existing Fields collection.  Dim a new Field object, specify its values and retry the operation with the new Field object.


Append illegal - Index is part of a TableDefs collection

An Index object was specified as an argument to an Indexes.Append operation when it already is a member of an existing Indexes collection.  Dim a new Index object, specify its values and retry the operation with the new Index object.


OLE Client Control

See Also	Properties	Events	Methods

Object linking and embedding (OLE) is a technology that allows a programmer of Windows-based applications to create an application that can display data from many different applications, and allows the user to edit that data from within the application in which it was created.  In some cases, the user can even edit the data from within the Visual Basic application.  Visual Basic's OLE client control provides an interface to this technology.

Distribution Note	When you create and distribute applications that use the OLE client control, you should install the files OLECLIEN.VBX, OLECLI.DLL and SHELL.DLL in the customer's Microsoft Windows \SYSTEM directory.  If you have the Visual Basic Professional Edition, the Visual Basic Setup Kit provides tools to help you write setup programs that install your applications correctly.

OLE Fundamentals  The following terms and concepts are fundamental to fully understanding the OLE client control.

Client Application  An application that receives and displays an object's data is referred to as a client application.  When a Visual Basic application uses an OLE client control to embed or link data from another application, it is a client application.

Server Application  An application which is used to produce and edit an object's data is referred to as a server application.  For example, if a Microsoft Excel spreadsheet were linked or embedded into a Visual Basic application using an OLE client control, the Visual Basic application would be the client and Microsoft Excel would be the server.

Linked and Embedded Objects  You can use an OLE client control to incorporate data into a Visual Basic application by linking or embedding data from another application.  Data associated with a linked object is stored by the server application; the OLE client stores only link references that enable display of snapshots of the source data.  Data associated with an embedded object is contained in an OLE client control and can be saved by the client application.  The server application then has access to the data only through the OLE client control.

When an object is linked to a Visual Basic application, the object's data can be accessed from any application that contains a link to that data and can be changed from within any of them.  For example, if a text file is linked to a Visual Basic application, it could be modified by any other application that was linked to it.  The modified version would appear in all the documents that had a link to this text file.

When you use an OLE client control to create an embedded object, all the data associated with the object is contained in the OLE client.  For example, if a spreadsheet were an embedded object, all the data associated with the cells would be contained in the OLE client control, including any necessary formulas.  The name of the server application is saved along with the data.  If the user selects the embedded object while working with the Visual Basic application, the spreadsheet application can be started automatically for editing those cells.  When an object is embedded into an application, no other application has access to the data in the embedded object.  Embedding is useful when you want only your application to maintain data that is produced and edited in another application.

As its name implies, the OLE client control can only be used to create client applications, not server applications.  The extent of interoperability between client and server is limited by the server.  For example, OLE offers the potential for a client to manipulate and modify the data for either linked or embedded objects from within the client application.  However, this is only possible in practice if the server application registers the necessary information in the registration database.  Similarly, since source data is in the format of the server application, manipulating or editing that data from within a Visual Basic application requires detailed knowledge of the server's data format.  In general, for linking or embedding, the user edits source data in the server application.  In the Visual Basic client application, the user displays and saves or links the data.

Using the OLE Client Control  To link or embed data in a Visual Basic application, you first set appropriate OLE client properties and then perform an action which creates an OLE object [image] that is, you set the Action property to a value that creates the type of OLE object you want.

Object Type

OleClient


Properties

Action	Index	ServerProtocol
BackColor	Left	ServerProtocolCount
BorderStyle	lpOleObject	ServerShow
Class	Name	ServerType
Data	Parent	ServerVerbs
DataText	PasteOK	ServerVerbsCount
DragIcon	Picture	SourceDoc
DragMode	Protocol	SourceItem
Execute	ServerAcceptFormats	Tag
FileNumber	ServerAcceptFormatsCount	TimeOut
Focus	ServerClass	Top
Format	ServerClassCount	UpdateOptions
Height	ServerClasses	Verb
HelpContextID	ServerClassesDisplay	Visible
HostName	ServerGetFormats	Width
hWnd	ServerGetFormatsCount


Events

Click	KeyDown	MouseMove
DblClick	KeyPress	MouseUp
DragDrop	KeyUp	Updated
DragOver	LostFocus
GotFocus	MouseDown


Methods

Drag	Refresh	ZOrder
Move	SetFocus


See Also

Help:

Open Statement

Picture Property

Using Custom Controls

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Action Property, OLE Client Control

See Also

Applies To

OLE client.

Description

Determines an action to take; not available at design time and write-only at run time.

Usage

[form.]oIeclient.Action = setting

Setting

By setting the Action property at run time, these operations can be performed:

Setting 	Description

0	CreateNew [image] creates a new instance of an OLE object.

To use this action, you must first set the Protocol, Class, and ServerType properties.  You must set the ServerType property to 1 (Embedded).  The Class property determines the type of OLE object created (for example, the class setting is "MSDraw" for a Microsoft Draw picture, "WordDocument" for a Microsoft Word document, and so on).

When you create a new OLE object, the executable file associated with the class name (for example, EXCEL.EXE) must either be active or on the system's path.  When the server application updates the client OLE object, the data shown is actually placed in the OLE object.  If you save the OLE object, the data is saved within the OLE object as well as in the server application.

1	CreateFromFile [image] creates a linked OLE object from the contents of a file.

To use this action, you must first set the Protocol, Class, ServerType, and SourceDoc properties.  You must set ServerType to 0 (Linked).  The Class property determines the type of OLE object created (for example, the Class setting is "MSDraw" for a Microsoft Draw picture, "WordDocument" for a Microsoft Word document, and so on).  The SourceDoc property specifies the file from which the OLE object is created.  You can also set the SourceItem property (for example a row/column range specification if the server is a Microsoft Excel worksheet).

When an OLE object is created with this action, the OLE client control simply displays an image of the SourceDoc.  If the OLE object is saved, only the link references are saved, since the client control contains only a metafile image of the data and no source data.  Therefore, the user cannot edit OLE objects created with this action from within Visual Basic.

When creating a new OLE object, the executable file associated with the class name (for example, EXCEL.EXE) must either be active or on the system's path.

2 	This number is reserved for future use.

3 	This number is reserved for future use.

4	Copy [image] places a copy of an OLE object on the Clipboard.

When an OLE object is copied to the Clipboard, all the data and link information associated with the object is placed on the Clipboard.  You can copy both linked and embedded objects to the Clipboard.

You can use this action to support an Edit Copy command.

5	Paste [image] copies data from the Clipboard to an OLE client control.

To use this action, set the Protocol and ServerType properties, and then check the value of the PasteOK property.  You cannot paste successfully unless PasteOK returns a value of True.

To Paste a linked or embedded OLE object, set Protocol to "StdFileEditing."  To Paste a static OLE object, set Protocol to "Static."

You can use this action to support an Edit Paste command.

See the PasteOK property topic for more information and an example.

6	Update [image] retrieves the current data from the server application and displays that data as a picture in the OLE client control.

This action applies to OLE objects that have been created with ServerType = 0 (Linked) or ServerType = 1 (Embedded).

7	Activate [image] opens an OLE object for an operation, such as editing.

To use this action, first set the Verb, ServerShow, and Focus properties.  The Verb property specifies the operation to perform when the OLE object is activated.

Generally, you'll want to perform this action in the DblClick event for the OLE client control.

8	Execute [image] sends a string to be executed to the server application.

You must first set the Protocol property to StdExecute.  The string to execute is specified in the Execute property.

This action is similar to Visual Basic's LinkExecute method, except that server applications can support different execute strings for OLE objects than for DDE conversations.

9	Close [image] closes an OLE object and terminates the connection with the server application.

This action is equivalent to the user selecting Close from the object's Control-menu box.

10	Delete [image] deletes the specified OLE object and frees the memory that was associated with it.

This action allows the programmer to explicitly delete an OLE object.  Objects are automatically deleted when a form is closed or when the object is updated to a new object.

11	SaveToFile [image] saves a client OLE object to a data file.

To use this action, first set the FileNumber property.  The FileNumber property must correspond to an open, binary file.

If the OLE object is linked (ServerType = 0, Linked), then only the link data is saved to the specified file.  The data in the object is maintained by the server application.  If the OLE object is embedded (ServerType = 1, Embedded), the actual data is saved and can be maintained by the client application.

See the FileNumber property topic for an example.

12	ReadFromFile [image] loads a client OLE object from a data file.

To use this action, first set the FileNumber property.  The FileNumber property must correspond to an open, binary file.

See the FileNumber property topic for an example.

13	ConvertToType [image] converts the current OLE object to the type specified by the ServerType property.

Currently, the only conversion that is supported by OLE is to change a linked or embedded OLE object to a static OLE object.  To do this, first set ServerType = 2 and Protocol = "Static."  If the server application supports the "Static" protocol, then the object will be converted when you set Action = 13.

Note	Constants for Action property settings are defined in Visual Basic's CONSTANT.TXT file.

DataType

Integer (Enumerated)


See Also

Help:

Class Property

Execute Property

FileNumber Property

Focus Property

PasteOK Property

Protocol Property

ServerShow Property

ServerType Property

SourceDoc Property

SourceItem Property

UpdateOptions Property

Verb Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Class Property

See Also

Applies To

OLE client.

Description

Determines the class name of an embedded OLE object.

Usage

[form.]oleclient.Class [ = classname ]

Remarks

A class name defines a type of OLE object that a server supports.  For example, Microsoft Excel supports three types of OLE objects [image] spreadsheets, charts, and macrosheets.  Their class names are "ExcelWorksheet," "ExcelChart," and "ExcelMacrosheet" respectively.  Note that most OLE server applications support only one type of OLE object.

This property determines the type of OLE object that is created when the Action property is set to CreateNew or CreateFromFile.  When creating a new object, the executable file associated with the specified class (for example, EXCEL.EXE) must either be active or on the system's path.

Use the ServerClasses and ServerClassCount properties to determine class names supported by server applications.

This property is updated when an embedded object is copied from the Clipboard [image] that is, when you set the Action property to 5 (Paste).  For example, if a Microsoft Excel chart is pasted from the Clipboard to an OLE object that previously contained a Microsoft Excel worksheet, the Class property changes from "ExcelGraph" to "ExcelWorksheet."

With some servers, the Class property is case-sensitive.  In general, it's a good idea to set an OLE object's Class property using data directly from the registration database.  For example:

OLEClient1.Class = OLEClient1.ServerClasses(x)

Data Type

String


See Also

Help:

Action Property

PasteOK Property

Protocol Property

ServerClasses Property

ServerClassCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Data Property

See Also

Applies To

OLE client.

Description

Determines a handle to a memory or graphical device interface (GDI) object that contains data in a specified format; not available at design time.

Usage

[form.]oleclient.Data [ = data ]

Remarks

You send data to a server by setting this property.  There is no guarantee, however, that a server will do anything with this data once it is received.

Set the Format property to determine the type of data contained in the memory or GDI object.  You must set this property before you can use the Data property.  You can get a list of acceptable formats for an OLE object using the ServerAcceptFormats and ServerGetFormats properties.

Setting this property to 0 frees the memory associated with the handle.

Data Type

Long


See Also

Help:

Format Property

Protocol Property

ServerAcceptFormats Property

ServerAcceptFormatsCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


DataText Property

See Also	Example

Applies To

OLE client.

Description

Determines a string from the specified OLE object; not available at design time.

Usage

[form.]oleclient.DataText [ = data ]

Remarks

This property is highly server-dependent.  There is no guarantee as to what string the server will send to the client, or what a server will do with a string that is sent to it.

When getting data from a server, the DataText property returns the string that is sent from the server, ending at the first null character.  Note that although DataText returns a text string, the contents of the string are in the format specified by the Format property.  You can get a list of formats that are supported by a server using the ServerGetFormats property.  See the server application's documentation for information on the formats that a particular server supports.

When setting the DataText property, you must pass a string in a format that the server accepts.  Again, you specify the format using the Format property.  You can get a list of formats that a server can accept using the ServerAcceptFormats property.  The DataText string must be less than 64K.

Data Type

String


See Also

Help:

Format Property

Protocol Property

ServerAcceptFormats Property

ServerAcceptFormatsCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


DataText Property Example

The example sends data to the Microsoft Graph application, so you must have Graph to run the example.  Create a form about half the size of the screen with an OLE client named OleClient1 in the top four-fifths of the form and a command button Command1 in the bottom one-fifth.  Start the Visual Basic application.

The Visual Basic application will transfer focus to the Microsoft Graph application with MS Graph's default data showing.  Choose Update from MS Graph's File menu, then click the Visual Basic application.  The default graph data appears in OleClient1.  Press the command button, and then click MS Graph to see that the data from the Visual Basic application has been transmitted to MS Graph.  Choose Exit and Return from the MS Graph File menu to see the data displayed in OleClient1.

Sub Form_Load ()

Show	' Display VB application.

OleClient1.Format = "CF_TEXT"	' Set up link to Graph.

OleClient1.Class = "MSGRAPH"

OleClient1.Action = 0	' Show default graph in

End Sub	' Graph application.

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 + "Me" & TB & "Myself" & TB & "I"

Msg = Msg + NL & "one" & TB & "1" & TB & "2" & TB & "3"

Msg = Msg + NL & "two" & TB & "11" & tb & "22" & TB & "33"

Msg = Msg + NL & "three" & TB & "21" & TB & "32" & TB & "23"

' Send the data through the DataText property.

OleClient1.DataText = Msg

End Sub


Execute Property

See Also

Applies To

OLE client.

Description

Specifies a string to execute.  Not available at design time.

Usage

[form.]oleclient.Execute [ = executestring ]

Remarks

The server application executes this string when the Action property is set to 8 (Execute).

Before setting the Action property, use the ServerProtocol and ServerProtocolCount properties to determine whether the server supports the "StdExecute" protocol, and then make sure the Protocol property is set to "StdExecute."

Although you can use this property to pass an execution string to a server application, it is up to the server to perform an action when it receives the string.  See the server application's documentation for information on the execution strings that it supports.

Note	The OLE execute strings that a server application supports aren't necessarily the same as the DDE execute strings that a server application supports.

Data Type

String


See Also

Help:

Protocol Property

ServerProtocol Property

ServerProtocolCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


FileNumber Property

See Also	Example

Applies To

OLE client.

Description

Determines the file number to be used when saving or loading an OLE object, or reflects the last file number used.  Not available at design time.

Usage

[form.]oleclient.FileNumber [ = filenumber ]

Remarks

The FileNumber must correspond to an open, binary file.

Use this property to specify the number of the file to be opened or saved when setting Action = 11 (Save) or Action = 12 (Read).

Data Type

Integer


See Also

Help:

Action Property

FreeFile Function

Open Statement

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


FileNumber Property Example

The example shows how to save and open the data associated with OleClient1 in a file named MYOB.OLE. To run the example you need Excel running or on your path. Create a form with an OLE Client control named OleClient1. Place a command button (Command1) on the form.  Place a menu named File on the form with two menu items: mnuOpenObject and the other named mnuSaveObject.

Press F5, then press the command button to set Protocol, Class, ServerType, and Action properties. Excel starts if it is not already running. Enter data in a spreadsheet, then choose Update from Excel' s File menu to show the data in the OLE client control. Choose Save from the example form's File menu. This creates the file in which the OLE object is saved. You can end the example application, start it again and choose Open Object from its File menu to display the object independent of Excel. Note that when you do so, the command button is disable.

Sub Command1_Click ()

OleClient1.Protocol = "StdFileEditing"

OleClient1.Class = "ExcelWorksheet"	' Set necessary

OleClient1.ServerType = 1	' properties, then

OleClient1.Action = 0	' create OLE object.

Show	' Show form with object,

Command1.Enabled = False	' then disable button...

End Sub

Sub mnuSaveObject_Click ()

Dim FileNum	' Declare variable.

FileNum = FreeFile	' Get a valid file number.

Open "MYOB.OLE" For Binary As FileNum	' Open file to be saved.

OLEClient1.FileNumber = FileNum	' Set the OLEClient filenumber.

OLEClient1.Action = 11	' Save the file.

Close #FileNum	' Close the file.

End Sub

Sub mnuOpenObject_Click ()

Dim FileNum	' Declare variable.

FileNum = FreeFile	' Get a valid file number.

Open "MYOB.OLE" For Binary As FileNum	' Open the file.

OLEClient1.FileNumber = FileNum	' Set the OLEClient filenumber.

OLEClient1.Action = 12	' Get data from OLEClient file.

Close #FileNum	' Close the binary file.

' Since you've opened the file, disable button that initiates the object

Command1.Enabled = False

End Sub


Focus Property

See Also

Applies To

OLE client.

Description

Determines whether a server application gets the focus when an OLE object is activated.

Usage

[form.]oleclient.Focus [ = boolean ]

Setting

The Focus property settings are:

Setting 	Description

True 	(Default) Indicates that the server application should receive the focus when the OLE object is activated.

False	Indicates that the server application should not receive the focus when the OLE object is activated.

Remarks

This property does not have any effect unless the ServerShow property is set to True.

When an OLE object is activated (Action = 7), this property communicates to the server application how the focus should be set.  Each server application may respond to this request differently.  Some servers may ignore the request, while others may perform unexpectedly.

Data Type

Integer (Boolean)


See Also

Help:

Action Property

ServerShow Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Format Property

See Also

Applies To

OLE client.

Description

Determines the format when setting and getting data from a server application.  Not available at design time.

Usage

[form.]oleclient.Format [ = format ]

Remarks

This property determines the format used with the Data and DataText properties.

Use the ServerAcceptFormats, ServerAcceptFormatsCount, ServerGetFormats, and ServerGetFormatsCount properties to get a list of the acceptable data formats for a specific class of OLE object.  Many server applications support only one or two formats.  For example, Microsoft Draw accepts only the CF_METAFILEPICT format.  Note that although CF_METAFILEPICT resembles the symbolic constant CF_METAFILE (numeric value 3) defined in CONSTANT.TXT, it is actually a string literal and would be assigned as:

OleClient1.Format = "CF_METAFILEPICT"

In many cases the list of formats that a server can accept (ServerAcceptFormats) is different from the list of formats that a server can provide (ServerGetFormats).

Data Type

String


See Also

Help:

Data Property

DataText Property

ServerAcceptFormats Property

ServerAcceptFormatsCount Property

ServerGetFormats Property

ServerGetFormatsCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


HostName Property

See Also

Applies To

OLE client.

Description

Determines the name of the client application.

Usage

[form.]oleclient.HostName [ = name ]

Remarks

When editing an OLE object, the HostName is displayed in the object's window title.  Each server application may respond to this request differently.  Some servers may ignore the request, while others may perform unexpectedly.

Data Type

String


See Also

Help:

ServerShow Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


lpOLEObject Property

See Also	Example

Applies To

OLE client.

Description

Specifies the address of the OLE object.  Not available at design time; read-only at run time.

Usage

[form.]oleclient.lpOleObject

Remarks

Pass the value specified in the lpOleObject property to Windows API calls that manipulate the OLE object.  The value is 0 if no object is currently displayed.  The address of the OLE object may change unexpectedly as the program runs, so you should recheck the lpOleObject property each time you use it.  If a call is made to a Windows API that makes a callback to the OLE client control, the result is unpredictable.

Data Type

Long


lpOleObject Property Example

The example cannot be run by itself, but the code can augment other examples. It uses the Windows API function OleQueryBounds (available in Microsoft Windows version 3.1) to determine the optimal size for an OLE object (as determined by the server application).  The first argument to the OleQueryBounds function requires a long pointer to an OLE object.  This pointer is provided by the lpOleObject property.  The second argument requires a pointer to a user-defined type.

The following code could be used to automatically resize an OLE object named OleClient1. Note the code preceding the OleClient1_Updated Sub procedure must appear in a separate code module. Create such a module with the File menu's New Module command. the OleClient1_Updated Sub procedure should be pasted into the form on which you draw OleClient1. For example, you could paste the OleClient1_Updated Sub into the Ole Filenumber example to automatically resize the OLE client control whenever the object is updated from Excel.

' Place this code in the Declarations section of any code module.

Type Rectangle

Left As Integer

Top As Integer

Right As Integer

Bottom As Integer

End Type

Global OleRect As Rectangle

Declare Function OleQueryBounds Lib "OLECLI" (ByVal lpOleObject As Long,aRect As Rectangle) As Integer

Sub OleClient1_Updated ( )

' Once an OLE object has been created, this procedure resizes the OLE

' client control to the dimensions specified by the server application.

' when the server application's Update command is selected.

Dim RetVal As Integer

RetVal = OleQueryBounds (OleClient1.lpOleObject, OleRect)

' If the function was successful.

If RetVal = 0 Then

' OleQueryBounds returns size in 1/100 millimeters.

' Remember to set the ScaleMode of form to millimeters.

OleClient1.Width = OleRect.Right / 100

OleClient1.Height = Abs(OleRect.Bottom / 100)

End If

End Sub


See Also

Help:

hWnd Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


PasteOK Property

See Also	Example

Applies To

OLE client.

Description

Specifies whether the contents of the Clipboard can be pasted into the OLE client control.  Not available at design time; read-only at run time.

Usage

[form.]oleclient.PasteOK

Remarks

When this property returns True, the contents of the Clipboard can be pasted into the OLE client control.

This property is dependent upon the Protocol and ServerType property settings.

To paste an object

1.	Set ServerType and Protocol properties using the table below.

2.	Check the value of PasteOK.

3	Set Action = 5 (Paste).

When ServerType is	Set Protocol to

0 (Linked)	StdFileEditing

1 (Embedded)	StdFileEditing

2 (Static)	Static

This property can be useful if your application supports an Edit Paste command.  If PasteOK is False, then the Edit Paste command should be disabled; otherwise it can be enabled.  Enable and disable menu commands by setting their Enabled property to True and False, respectively.

Data Type

Integer (Boolean)


See Also

Help:

Enabled Property

Protocol Property

ServerType Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


PasteOK Property Example

The example code cannot run by itself, but illustrates how to synchronize the ServerType and Protocol properties, then paste the contents of the Clipboard into the OLE client control when the user chooses the appropriate menu item. To see how this works in an application, load the sample program OLEDEMO.MAK, and place a breakpoint in the mnuEditClick procedure, then press F5 and choose Paste from the Edit menu.

Sub mnuEditPaste_Click ()

' Synchronize properties to enable Paste.

If OLEClient1.ServerType = 2 Then

OLEClient1.Protocol = "Static"

Else

OLEClient1.Protocol = "StdFileEditing"

End If

' Check value of PasteOK.

If OLEClient1.PasteOK Then

OLEClient1.Action = 5	' Do the Paste if OK.

Else	' Otherwise disable Paste

mnuEditPaste.Enabled = False	' menu item and give

MsgBox "Cannot Paste"	' appropriate message.

End If

End Sub


Protocol Property

See Also

Applies To

OLE client.

Description

Determines the protocol used when a new OLE object is created.  The default value is the string literal StdFileEditing, which is the protocol most commonly supported by server applications.

Usage

[form.]oleclient.Protocol [ = protocol ]

Setting

The Protocol property settings are:

Setting	Description

StdFileEditing	(Default) Creates an OLE object that can be edited by the user.  OLE objects created with this protocol can also send execution strings to the server application.

StdExecute	Creates an OLE object that can pass execution strings to the server application but cannot be edited.

Static	Creates an OLE object that can be edited until the server application is closed.  Once the server application has been closed, the OLE object cannot be reeditied.  Using this protocol is similar to cutting and pasting data from one application to another.  Use this protocol when ServerType = 2 (Static).

Remarks

Currently, most applications support only StdFileEditing.  Note that the protocol settings are string expressions, not symbolic constants.  You can create a list of the protocols supported by a specific ServerClass using the ServerProtocol and ServerProtocolCount properties.

Data Type

String


See Also

Help:

ServerClass Property

ServerProtocol Property

ServerProtocolCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerAcceptFormats Property

See Also	Example

Applies To

OLE client.

Description

Specifies the list of formats that the server can accept.  The server is determined by the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerAcceptFormats (index)

Remarks

ServerAcceptFormats is a zero-based array of strings describing the valid formats that can be used in the Format property when exchanging data with a server using the Data and DataText properties.  ServerAcceptFormatsCount specifies the number of elements in the ServerAcceptFormats array.

The list of acceptable formats is obtained from the system's registration database.

Data Type

String


See Also

Help:

Data Property

DataText Property

Format Property

ServerAcceptFormatsCount Property

ServerClass Property

ServerClassCount Property

ServerClasses Property

ServerGetFormats Property

ServerGetFormatsCount Property

ServerProtocol Property

ServerProtocolCount Property

ServerVerbs Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


 Example Illustrating ServerAcceptFormats, ServerAcceptFormatsCount, ServerClassCount, ServerClasses, ServerClassesDisplay, ServerProtocol, ServerVerbs, ServerVerbsCount, ServerGetFormats, ServerGetFormatsCount Properties

The example code is for illustrative purposes. To run it you could paste it into the declarations section of a form, then place six listboxes on the form having the names ClassesList, ClassesDisplayList, ProtocolsList, VerbsList, AcceptFmtsList, and GetFmtsList. If you press F5, the registration database is opened and procedures fill each listbox with appropriate information. However, it is probably easier to see how this type of code works by just opening the sample application REGVIEW.MAK and pressing F5.The sample application displays information from the registration database in six list boxes.  The first list box displays all the ServerClasses in the registration database.  When the user selects a class from this list box, information such as the Protocols, Verbs, and Formats that the class accepts are displayed.

Sub Form_Load ()

Dim I	' Declare variable.

' Fill the ClassesList and ClassesListDisplay list boxes.

For I = 0 To OLEClient1.ServerClassCount - 1

ClassesList.AddItem OLEClient1.ServerClasses(I)

ClassesListDisplay.AddItem OLEClient1.ServerClassesDisplay(I)

Next I

End Sub

Sub ClassesList_Click ()

' When user selects a Class, highlight the associated ClassDisplay.

ClassesListDisplay.ListIndex = ClassesList.ListIndex

' Display information associated with the selected Class.

FillItems (OLEClient1.ServerClasses(ClassesList.ListIndex))

End Sub

Sub ClassesListDisplay_Click ()

' When user selects a ClassDisplay, highlight the associated Class.

ClassesList.ListIndex = ClassesListDisplay.ListIndex

End Sub

Sub FillItems (S )

Dim I	' Declare variable.

OLEClient1.ServerClass = S 	' Set the ServerClass.

' PROTOCOL.

While ProtocolsList.ListCount

ProtocolsList.RemoveItem 0	' Remove existing items.

Wend

'Fill the Protocol list box.

For I = 0 To OLEClient1.ServerProtocolCount - 1

ProtocolsList.AddItem OLEClient1.ServerProtocol(I)

Next I

' VERBS.

While VerbsList.ListCount

VerbsList.RemoveItem 0	' Remove existing items.

Wend

' Fill the VerbsList list box.

For I = 0 To OLEClient1.ServerVerbsCount - 1

VerbsList.AddItem OLEClient1.ServerVerbs(I)

Next I

' ACCEPTFORMATS.

While AcceptFmtsList.ListCount

AcceptFmtsList.RemoveItem 0	' Remove existing items.

Wend

'Fill the AcceptFmtsList list box.

For I = 0 To OLEClient1.ServerAcceptFormatsCount - 1

AcceptFmtsList.AddItem OLEClient1.ServerAcceptFormats(I)

Next I

' GETFORMATS.

While GetFmtsList.ListCount

GetFmtsList.RemoveItem 0	' Remove existing items.

Wend

' Fill the GetFmtsList list box.

For I = 0 To OLEClient1.ServerGetFormatsCount - 1

GetFmtsList.AddItem OLEClient1.ServerGetFormats(I)

Next I

End Sub


ServerAcceptFormatsCount Property

See Also	Example

Applies To

OLE client.

Description

Specifies the number of formats that can be accepted by the server.  The server is specified by the ServerClass property.  Not available at design time; read-only at run time.

Usage

[form.]oleclient.ServerAcceptFormatsCount

Remarks

Use this property to get the number of elements in the ServerAcceptFormats property array.

Data Type

Integer


See Also

Help:

Data

DataText

Format

ServerAcceptFormats

ServerClass

ServerClassCount

ServerClasses

ServerGetFormats

ServerGetFormatsCount

ServerProtocol

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerClass Property

See Also	Example

Applies To

OLE client.

Description

Determines a server class for later queries into the registration database; not available at design time.

Usage

[form.]oleclient.ServerClass [ = class ]

Remarks

Use this property before querying the registration database with the ServerAcceptFormats, ServerGetFormats, ServerProtocol, and ServerVerbs properties.  Values specified in these properties are determined by the value in ServerClass.

Data Type

String


See Also

Help:

Data

DataText

Format

ServerAcceptFormats

ServerClassCount

ServerClasses

ServerClassesDisplay

ServerGetFormats

ServerGetFormatsCount

ServerProtocol

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerClassCount Property

See Also	Example

Applies To

OLE client.

Description

Specifies the number of classes in the registration database; not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerClassCount

Remarks

Use this property to find out the number of elements in the ServerClasses and ServerClassesDisplay property arrays.

Data Type

Integer


See Also

Help:

ServerAcceptFormats

ServerClasses

ServerClassesDisplay

ServerGetFormats

ServerGetFormatsCount

ServerProtocol

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerClasses Property

See Also	Example

Applies To

OLE client.

Description

Specifies the list of class names obtained from the registration database; not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerClasses (index)

Remarks

The ServerClasses property is a zero-based string array of all the valid class names in the registration database.

This property returns an empty string ("") if index is out of range.  Use the ServerClassCount property to get the number of classes in the registration database.

Data Type

String


See Also

Help:

Data

DataText

Format

ServerAcceptFormats

ServerClassCount

ServerClassesDisplay

ServerGetFormats

ServerGetFormatsCount

ServerProtocol

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerClassesDisplay Property

See Also	Example

Applies To

OLE client.

Description

Specifies the list of class display names obtained from the registration database; not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerClassesDisplay (index)

Remarks

The list is a zero-based string array of class display names.  Each class of OLE objects has a corresponding display name.  A class display name is the name that is displayed in the title bar when an OLE object is created or edited.  For example, the class name for a Microsoft Excel spreadsheet is "ExcelWorksheet."  The corresponding class display name is "Excel Worksheet."

This property returns an empty string ("") if index is out of range.  Use the ServerClassCount property to get the number of classes in the registration database.

Data Type

String


See Also

Help:

ServerClassCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerGetFormats Property

See Also	Example

Applies To

OLE client.

Description

Specifies a list of formats for data interchange with servers in the registration database.  The contents of the list depend on the value of the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerGetFormats (index)

Remarks

The list is a zero-based string array.  Elements of the array can be used to set the Format property when getting data from a server using the Data and DataText properties.

The list of valid formats is obtained from the system's registration database.

Data Type

String


See Also

Help:

Data

DataText

Format

ServerAcceptFormats

ServerClassCount

ServerClassesDisplay

ServerGetFormatsCount

ServerProtocol

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerGetFormatsCount Property, OLE Client Control
ServerGetFormatsCount Property

See Also	Example

Applies To

OLE client.

Description

Specifies the number of formats a server can provide.  The value varies depending on the value of the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerGetFormatsCount

Remarks

Use this property to determine the number of elements in the ServerGetFormats property array.

Data Type

Integer


See Also

Help:

Data

DataText

Format

ServerAcceptFormats

ServerAcceptFormatsCount

ServerClassCount

ServerClasses

ServerProtocol

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerProtocol Property, OLE Client Control
ServerProtocol Property

See Also	Example

Applies To

OLE client.

Description

Specifies a list of the protocols supported by a server.  The contents of the list depend on the value of the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerProtocol (index)

Remarks

This property is a zero-based string array of the valid protocols that can be used in the Protocol property when creating a new OLE object.  The ServerProtocolCount property specifies the number of elements in the array.

The list of acceptable protocols is obtained from the system's registration database.

Data Type

String


See Also

Help:

Action

Data

DataText

Format

ServerAcceptFormats

ServerAcceptFormatsCount

ServerClassCount

ServerClasses

ServerProtocolCount

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerProtocolCount Property

See Also	Example

Applies To

OLE client.

Description

Specifies the number of protocols supported by a server.  The contents of the list depend on the value of the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerGetProtocolCount

Remarks

Use this property to determine the number of elements in the ServerProtocol property array.  The server is specified by the ServerClass property.

Data Type

Integer


See Also

Help:

Data

DataText

Format

ServerAcceptFormats

ServerAcceptFormatsCount

ServerClassCount

ServerClasses

ServerGetFormats

ServerProtocol

ServerVerbs

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerShow Property

See Also

Applies To

OLE client.

Description

Determines whether the server application is displayed when an OLE object is created.

Usage

[form.]oleclient.ServerShow [ = boolean ]

Remarks

Setting 	Description

True 	(Default) Indicates that when an OLE object is activated (OleClient.Action = 7), the server application should be displayed.

False	Indicates that when an OLE object is activated (OleClient.Action = 7), the server application should not be displayed.

When an OLE object is activated, this property communicates to the server application whether or not it should display itself.  Each server application may respond to this request differently.  Some servers may ignore the request, while others may perform unexpectedly.

Data Type

Integer (Boolean)


See Also

Help:

Action Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerType Property, OLE Client Control
ServerType Property

See Also

Applies To

OLE client.

Description

Determines the type of link between the client control and the server application.

Usage

[form.]oleclient.ServerType [ = linktype ]

Remarks

The ServerType property settings are:

Setting	Description

0 	(Default) Linked.  All the OLE object's data is managed by the server application.  When the object is saved (Action = 11), only link information such as SourceDoc, SourceItem, and so on, is saved in the specified file.

1	Embedded.  All the OLE object's data is managed with the Visual Basic application.  When the object is saved (Action = 11), all the data associated with the OLE object is saved in the specified file.

2	Static.  No data is saved.  At the time the OLE object is created, a snapshot of the server is displayed through the OLE client control.

The ServerType property determines the type of connection that is made to the server when a new OLE object is created.  You must also set the Action property when creating a new object, as well as the FileNumber property when saving and opening OLE client objects.

Data Type

Integer


See Also

Help:

Action Property

FileNumber Property

Protocol Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerVerbs Property

See Also	Example

Applies To

OLE client.

Description

Specifies a list of the verbs that can be supported by a server.  The verbs included in the list depend on the value of the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerVerbs (index)

Remarks

ServerVerbs is a zero-based string array.  Use this property along with the ServerVerbsCount property to get the verbs supported by a server.  These verbs are used by the Verb property to determine an action to perform when an OLE object is activated.

Data Type

String


See Also

Help:

Action Property

Protocol Property

ServerVerbsCount Property

Verbs Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


ServerVerbsCount Property

See Also	Example

Applies To

OLE client.

Description

Specifies the number of verbs supported by a server.  The value in ServerVerbsCount depends on the value of the ServerClass property.  Not available at design time and read-only at run time.

Usage

[form.]oleclient.ServerVerbsCount

Remarks

Use this property to determine the number of elements in the ServerVerbs property array.

Data Type

Integer


See Also

Help:

Action Property

Protocol Property

ServerVerbs Property

Verbs Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


SourceDoc Property

See Also	Example

Applies To

OLE client.

Description

Determines the file name to use when you create an OLE object from a file (Action = 1).

Usage

[form.]oleclient.SourceDoc [ = filename ]

Remarks

ServerType must be set to 0 (Linked) when SourceDoc is set.  Use the SourceItem property to specify data within the file to be linked.

This property is similar to Visual Basic's LinkTopic property.

Data Type

String


See Also

Help:

Action Property

Class Property

Protocol Property

ServerType Property

SourceItem Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


SourceDoc, SourceItem Property Example

The example creates a linked OLE object when the user clicks the command button  First, use Excel to create a spreadsheet named OLETEST.XLS.  Then create a form with an OLE client control (Protocol = "StdFileEditing" and ServerType = 0 (Linked)) named OleClient1.  Place a command button on the form and copy the following code into the form's declarations section, then press F5. The file OLETEST.XLS must exist in the specified path.

Sub Command1_Click

' Set class.

OleClient1.Class = "ExcelWorksheet"

' Specify source file.

OleClient1.SourceDoc = "C:\EXCEL\OLETEST.XLS"

' Specify the data within the file to be linked.

OleClient1.SourceItem = "R1C1:R5C5"

' Create a linked object using OleTest.xls.

OleClient1.Action = 1

OleClient1.Refresh	' Show the worksheet

End Sub


SourceItem Property

See Also	Example

Applies To

OLE client.

Description

Determines the data within the file to be linked when you create an OLE object from a file (Action = 1).

Usage

[form.]oleclient.SourceItem [ = stringexpression ]

Remarks

ServerType must be set to 0 (Linked) when using this property.  ServerDoc must specify the file.

Each server application uses its own syntax to describe units of data.  To set this property, specify a unit of data that is recognized by the server application.  For example, when you link to Microsoft Excel, you can specify the SourceItem using a cell or cell-range reference such as "R1C1" or "R3C4:R9C22."

This property is similar to Visual Basic's LinkItem property.

Data Type

String


See Also

Help:

Action Property

Class Property

Protocol Property

ServerType Property

SourceDoc Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


TimeOut Property

See Also

Applies To

OLE client.

Description

Determines the amount of time Visual Basic waits for a response from the server application when data has been requested.

Usage

[form.]oleclient.TimeOut [ = time ]

Remarks

TimeOut is measured in tenths of a second.  The default is 32,767.

During run time, the client application periodically requests data from the server application.  Most of these requests occur without informing the user.  For example, when an OLE object is updated, the client application requests that the server application send the most recent data so it can repaint the area within the OLE client control.  If the client application requests information from the server application and the amount of time specified by the TimeOut property passes before the server responds, the connection to the server application may no longer be valid.

Data Type

Integer


See Also

Help:

Action Property

Updated Event

UpdateOptions Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


UpdateOptions Property

See Also

Applies To

OLE client.

Description

Determines the type of link that is made to a server application.  Not available at design time.

Usage

[form.]oleclient.UpdateOptions [ = option ]

Remarks

The UpdateOptions property settings are:

Setting 	Description

0 	(Default) Automatic.  The OLE client control is updated each time the linked data changes.

1	Frozen.  The OLE client control is updated whenever the user saves the linked document from within the server application.

2	Manual.  The OLE client control is updated only when the Action property is set to 6 (Update).

This property applies only to OLE objects that have been created with ServerType = 0 (Linked).

Data Type

Integer (Enumerated)


See Also

Help:

Action Property

Class Property

Protocol Property

ServerType Property

TimeOut Property

Updated Event

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Verb Property

See Also

Applies To

OLE client.

Description

Specifies an operation to perform when an OLE object is activated (Action = 7).

Usage

[form.]oleclient.Verb [ = verbnumber ]

Remarks

Each server application can support its own set of verbs.  Currently, most server applications only support the verbs "edit" and "play."

Use the ServerVerbs and ServerVerbsCount properties to access the list of verbs that are supported by a specified server.  Set Verb = 0 to specify the first verb in the list, set Verb = 1 to specify the second verb in the list, and so on.

Data Type

Integer


See Also

Help:

Protocol Property

ServerType Property

ServerVerbs Property

ServerVerbsCount Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Updated Event

See Also	Example

Applies To

OLE client.

Description

Occurs when the server application has updated an OLE object.

Syntax

Sub OLEClient_Updated (Code As Integer)

Remarks

Code indicates how the OLE object was updated.  Its possible values are:

Value	Constant	Description

0	OLE_CHANGED	Indicates that the object has been changed.  When this occurs, a typical action is to save the object.

1	OLE_SAVED	The object has been saved by the server.  This usually occurs when the user selects the server's update command.

2	OLE_CLOSED	The object has been closed by the server.

5	OLE_RELEASE	The server has completed an operation and released the object to the client.

This event is useful for determining if the data in an embedded OLE object has been changed since it was last saved.  To do this, set a global variable in the Update event indicating the object needs to be saved.  When you save the OLE object, reset the variable.  The constants are defined in the file CONSTANT.TXT.


See Also

Help:

Action Property

Class Property

Protocol Property

ServerType Property

UpdateOptions Property

Programmer's Guide:

Chapter 21, "Object Linking and Embedding (OLE)"


Updated Event Example

The example code below is for illustration purposes only.  To see how it works, just load the sample application project OLEDEMO.MAK and press F5. The example uses a global variable to determine if a menu item should be dimmed.

' Place this declaration in the module level of a code module.

Global Save As Integer

Sub OleClient1_Updated (code As Integer)

' Set flag indicating that the object needs to be saved.

Save = -1

End Sub

Sub mnuFile_Click ()

' When the File menu is selected, if the object needs to be

' saved, then enable the SaveObject menuitem.

' Otherwise, disable the SaveObject menu item.

If Save Then

mnuSaveObject.Enabled = -1

Else

mnuSaveObject.Enabled = 0

End If

End Sub

Sub mnuSaveObject_Click ()

' Save the object, reset global variable when done.

Dim FileNum

' Set filter for File Save dialog.

CMDialog1.Filter = "Ole Files (*.ole)|*.ole|"

' Display File Save dialog.

CMDialog1.CancelError = -1

On Error Resume Next

CMDialog1.Action = 2

If (Err) Then

MsgBox "Object not saved!", 16, "Ole Sample Application"

Else

' Open file.

FileNum = FreeFile

Open CMDialog1.FileName For Binary As #FileNum

OLEClient1.FileNumber = FileNum

' Save the selected file.

OLEClient1.Action = 11

Close #FileNum

' Object saved, reset global variable.

Save = 0

End If

End Sub


Displaying or Hiding the Grid

See Also

When you're in design mode, the Form window displays a grid comprised of dots or points, the distance between which is measured in twips.  Use the grid to ensure that controls are positioned uniformly on a form.  You can display or hide the grid.

To display or hide the grid

1.	From the Options menu, choose Environment.

2.	Scroll down to select Show Grid.

3.	In the Setting box, select either Yes or No to display or hide the grid.

4.	Choose OK.


See Also

Help:

Aligning an Item to the Grid

Changing Grid Spacing

Programmer's Guide:

Chapter 5, "Managing Projects"


Changing Grid Spacing

See Also

You can adjust the spacing of the grid points displayed in the active Form window.  You specify grid spacing in pixels.

To change grid spacing

1.	From the Options menu, choose Environment.

2.	Scroll down and select Grid Width.  In the Setting box, type the width you want between horizontal points.

3.	Click the Enter button to accept the edit, or click the Cancel button to cancel the edit.

4.	Select Grid Height.  In the Setting box, type the height you want between vertical points.

5.	Click the Enter button to accept the edit, or click the Cancel button to cancel the edit.

6.	Choose OK.


See Also

Help:

Aligning an Item to the Grid

Displaying or Hiding the Grid

Programmer's Guide:

Chapter 5, "Managing Projects"


Displaying Graphics on a Form

See Also

You can add graphics to forms and controls at design time by setting the Picture property in the Properties window or by copying graphics from other applications and pasting them into Visual Basic.  A graphic can be displayed either as a foreground graphic, using a picture box or image control as the display area for a bitmap, icon, or metafile, or as a background graphic, using the entire Form window as the display area.  You can also add graphics at run time with code.

To add a foreground graphic at design time using the Properties window

1.	Draw a picture box or image control on the form.

2.	In the Properties window, select Picture.

In the Settings box, Visual Basic displays the current type of image and the down arrow to the right of the Settings box changes into a button with three dots.

3.	Click the button with three dots.

Visual Basic displays the Load Picture dialog box.

4.	In the dialog box, select or type the name of the graphic file you want.

5.	Choose OK.

Visual Basic displays the graphic inside the picture box.  If necessary, resize the picture box.

To add a background graphic at design time using the Properties window

1.	Click a blank part of the form to select it.

2.	From the Properties window, select Picture.

3.	Follow steps 3-5 as listed above.

Visual Basic displays the graphic inside the Form window.  If necessary, resize the form.

To add a graphic at design time by copying and pasting

1.	Open the other application and copy the graphic to the Clipboard.

2.	Switch to Visual Basic.

3.	Select the form or control onto which you want to paste the graphic.

4.	From the Edit menu, choose Paste (Ctrl+V).

Note	To delete a graphic at design time, select the Picture property in the Properties window and delete the contents of the Settings box.

Full-screen bitmaps for forms can be memory-intensive.  To save memory, use a picture box or image control to display a foreground graphic.

When using a Picture box, set the AutoSize property to True to automatically resize the control to fit the picture.  When Autosize is set to False, the size of the control remains constant and graphics are clipped when they exceed the area of the control.


See Also

Help:

Drawing Lines and Shapes on a Form

Form

Picture Box Control

Setting Form and Control Properties

Using Icons

Learning Visual Basic:

Using Color and Graphics

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Drawing Lines and Shapes on a Form

See Also

You can use the line control to draw simple lines on forms, and the shape control to draw rectangles (regular or rounded corners), squares (regular or rounded corners), ovals, and circles on forms.  Select each tool in the Toolbox.

To draw a line a form

1.	In the Toolbox, select the line control.

When the pointer moves onto the form, it changes to a cross hair.

2.	Click the form where you want the line to begin and hold down the mouse button.

3.	Drag the cross hair to where you want the line to end and release the mouse button.

4.	From the Properties window, select the BorderStyle property if you want to change the appearance of the line.

5.	In the Settings box, select the style you want.

6.	Click the Enter button to accept the setting.

To draw a shape on a form

1.	In the Toolbox, select the shape control.

When the pointer moves onto the form, it changes to a cross hair.

2.	Click and drag the cross hair to make the item the size you want.

3.	From the Properties window, select the Shape property.

4.	In the Settings box, select the style you want.

5.	Click the Enter button to accept the setting.

Note	To add color, set the BackColor property to the color you want.

To draw lines, rectangles, and filled-in boxes at run time, use the Line method.

To draw circles, ellipses, and arcs at run time, use the Circle method.


See Also

Help:

Displaying a Graphic on a Form

Picture Box Control

Setting Form and Control Properties

Learning Visual Basic:

Using Color and Graphics

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Drawing a Control

See Also

A control is a graphical object drawn with the tools in the Toolbox.  Each control has a set of properties, events, and methods that can be used to add specialized functionality to your application.

To draw a control

1.	In the Toolbox, select the tool you want.

2.	Click the form where you want to place the control.

As you move the pointer onto the form, it changes to a cross hair.

3.	Click and drag the cross hair to make the item the size you want.

Drawing shortcut

In the Toolbox, double-click the tool you want.

The control appears in the center of the form.  Move and resize it as desired for your application.

Note	Option buttons always work as part of a group.  Selection of one button within a container immediately clears all other buttons in the group.  If you want to create more than one option group on a form, draw each set of option buttons inside a frame or picture box.

For details on the properties, events, and methods that pertain to each control, see the individual control topics under Controls.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Creating a Control Array

Setting Form and Control Properties

Learning Visual Basic:

Creating an Application

Working with Forms and Controls

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"


Creating a Control Array

See Also

A control array is made up of a group of controls of the same type (for example, all list boxes) that share a common control name and a set of event procedures.  Each control in the array has a unique index number.  All items in a control array must have the same setting of the Name property.

To create a control array

1.	Draw the controls for the array.

2.	Select a control you want to include in the array.

3.	From the Properties window, select the Name property.

4.	Int the Settings box, type a name for the control.

5.	Choose the Enter button.

6.	Repeat steps 2-5 for each control you want in the array, typing the same name as in step 4.

When you type the same Name for the second control, Visual Basic displays a dialog box asking you to confirm that you want to create a control array.

7.	Choose Yes to create the control array, or choose No to cancel the action.

Note	To remove a control from a control array, change the control's Name property.

When a control in the array recognizes an event, Visual Basic calls an event procedure for the group and passes the index as an additional argument, allowing you to determine which control recognizes the event.

Event procedures for control arrays are defined with the argument "(Index as Integer)."


See Also

Help:

Adding and Deleting Controls at Run Time

Creating a Menu Bar

Creating a Menu Control Array

Index Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Adding and Deleting Controls at Run Time

See Also	Example

Because control arrays in Visual Basic are dynamic, you can add or delete controls in a control array at run time.  However, you must first create a control array that contains at least one control at design time, and then you can write code (using the Load and Unload statements) to dynamically add or delete controls from the array at run time.

To add or delete controls in a control array at run time

1.	Create a control array.

If you are creating a control array only so you can add controls at run time, you can accomplish this by simply setting the Index property for a single control at design time.

2.	Open the Code window by double-clicking a control in the control array.

3.	Go to the event or procedure where you want to load or unload members of the control array and write the appropriate code.

Note	At run time, you cannot remove controls created at design time.


See Also

Help:

Creating a Menu Bar

Creating a Menu Control Array

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Adding and Deleting Controls at Run Time Example

To try this example, paste the code into the Declarations section of a form containing one option button, two command buttons, and a large picture box.  Set the Index property for the option button to 0 to create a control array.  Set the Caption property to "Add" for one command button and "Delete" for the other.  Then press F5.  Each time an option button is clicked, the BackColor property of the picture box is reset.  Clicking a command button causes an option button to be added or deleted depending on which one is chosen.

Dim MaxId	' Declare variable.

Sub Option1_Click (Index As Integer)

Picture1.BackColor = QBColor(Index + 1)

End Sub

Sub Command1_Click ()

If MaxId >= 9 Then Exit Sub	' No more than 10 buttons.

MaxId = MaxId + 1	' Increment button count.

Load Option1(MaxId)	' Create new button.

Option1(0).SetFocus	' Reset button selection.

' Set new button under previous button.

Option1(MaxId).Top = Option1(MaxId - 1).Top + 360

Option1(MaxId).Visible = True	' Display new button.

End Sub

Sub Command2_Click ()

If MaxId = 0 Then Exit Sub	' Keep first button.

Unload Option1(MaxId)	' Delete last button.

MaxId = MaxId - 1	' Decrement button count.

Option1(0).SetFocus	' Reset button selection.

End Sub


Selecting Controls

See Also

To select a control

In the Form window, click the control you want.

To select multiple controls

1.	In the Form window, click one of the controls you want to select.

2.	With the control selected, press and hold down the Ctrl key, and then click each additional control you want to select.  You can deselect a control in a selection by holding down the Ctrl key and clicking the control.

Or

In the Form window, click and drag a box around the controls you want to select.

Note	To select multiple controls within a container (a frame or picture box), first deselect the container.  Then while pressing the Ctrl key, click and drag a box around the controls that you want to select.

Once you have selected multiple controls, you can change the setting of properties the controls have in common with one change in the Properties window.

To cancel a selection

Click anywhere on the form outside of the selected item.


See Also

Learning Visual Basic:

Working with Forms and Controls

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"


Aligning an Item to the Grid

See Also

You can automatically or manually align items to the grid as you draw them in the Form window.  In either case, the grid doesn't have to be visible.

To automatically align items to the grid as you draw them

1.	From the Option menu, choose Environment.

2.	Scroll down to select Align To Grid.

3.	In the Setting box, choose Yes.

To manually align an item to the grid

1.	Select the item or items you want to align.

2.	From the Edit menu, choose Align to Grid.


See Also

Help:

Changing Grid Spacing

Displaying or Hiding the Grid


Creating a Menu Bar

See Also

You can use the Menu Design window to create a menu bar that displays the names of menus available to use in the active window.  You can also write code to make your menu respond dynamically to user preferences or run-time conditions, such as whether a menu command should be unavailable, or whether menu commands should be added or deleted.

To create a menu bar

1.	Click the form for which you want to create a menu bar.

2.	From the Window menu, choose Menu Design (Ctrl+M), or use the toolbar shortcut:

3.	In the Caption text box, type the menu item caption as you want it displayed on the menu bar.

To give the user keyboard access to the menu item, type an ampersand (&) before the letter you want to specify as the access key.  At run time, this letter is underlined, and the user can access the menu or command by pressing Alt plus the access key.

To create a separator bar in your menu, type a single hyphen (-) in this box.

4.	In the Name text box, type a control name that you'll use to refer to the menu item in code.  This name can be identical to the caption.

5.	Use the left and right arrows to change the level of a menu item (from a higher level to a lower level or vice versa.)  You can have up to four levels of submenus.

Use the up and down arrows to change the position of a menu item (up or down in the list box.)

Choose Next to move to the next line and add another item to the menu.

Choose Insert to add a line before the currently selected line.

Choose Delete to delete the currently selected line.

6.	Repeat steps 3-5 to add menu items.

7.	Choose OK to accept all the changes and apply them to the selected form.

The menu you created is visible at design time, but no events are generated until you write code.

Optional features for custom menus:

In the Index text box, type a number that determines the control's position within the control array.

To assign a shortcut key to a menu item, select a key from the Shortcut drop-down list.

Select the Window List check box if you want the current menu control to include the name of open MDI child forms.

Enter a unique number in the HelpContextID if you plan to provide a context-sensitive Help topic for the current control.

Select the Checked box if you want a small check mark to appear at the left of a menu item to indicate that the control is turned on or to indicate which of several modes is in effect.

Select the Enabled box if you want the menu item to initially respond to events.  Clear the box if you want the menu item to be unavailable and appear dimmed on the menu.  An initially unavailable item can later be enabled in code.

Select the Visible box if you want the menu item to appear on the menu.

Note	For details on the properties, events, and methods that apply to menus, see the Menu topic.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Creating a Menu Control Array

Specifying Access Keys

Learning Visual Basic:

Adding Menus

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Creating a Menu Control Array

See Also

A menu control array is made up of one or more menu items that share a common name and event procedures.  Each menu item has a unique index number, but all the items share the same setting of the Name property.  You can designate one or more contiguous menu items at the same menu level as a control array.  This enables you to dynamically add or remove menu items during run time.

To create a menu control array with one menu item

1.	Create the menu item.

2.	In the Index text box, enter a number.

To create a menu control array with more than one menu item

1.	Create a menu item.

2.	In the Index text box, enter a number.  This number determines the menu item's position in the control array.

3.	Create another menu item with the same control name.

4.	In the Index text box, enter a unique number.

5.	Repeat steps 2-4 for each additional menu item.

Note	When a control in the array recognizes an event, Visual Basic calls an event procedure for the group and passes the index as an additional argument, allowing you to determine which control recognizes the event.


See Also

Help:

Adding and Deleting Controls at Run Time

Attaching an Event Procedure to a Form or Control

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Adding and Deleting Menu Commands at Run Time

See Also

After using the Menu Design window to create a control array with one or more menu items, you can write code (using the Load and Unload statements) to dynamically add or delete menu items in the array at run time.

To add or delete menu items in a control array at run time

1.	Create a menu control array.

2.	Open the Code window by double-clicking a control or the form itself.

3.	Go to the event or procedure where you want to Load or Unload members of the control array.

Note	At run time, you cannot remove commands created at design time.


See Also

Help:

Adding and Deleting Controls at Run Time

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Setting Form and Control Properties

See Also

Properties are named attributes of a form or control.  They define an object's characteristics, such as size, color, and screen location, and aspects of the object's behavior, such as whether it is enabled or not.  You can set properties in the Properties window at design time, and in code at run time.

To set form or control properties in the Properties Window at design time

1.	Click a blank part of a form to select the form; or click a control to select the control.

2.	From the Window menu, choose Properties (F4), or use the toolbar shortcut:

3.	From the Properties window, select the property you want either by clicking the property name in the Property list or by pressing Ctrl+Shift+ the first letter of the property name you want to select.  If several properties begin with the same letter, continue pressing Ctrl+Shift+ the first letter key until the property you want is selected.

Visual Basic displays the current setting for the property in the Settings box.

4.	In the Settings box, enter the setting you want.

For a property that requires entering text or a number, type the information.

For a property that has enumerated or Boolean values, click the down arrow to the right of the Settings box and select the option you want from the combo box or double-click the property name to cycle through the list of available choices.

For a number of properties, the down arrow changes into a button with three dots.  Click this button to display a dialog box in which you select the settings for the property.

5.	Click the Enter button to accept the setting or click the Cancel button to cancel it.

6.	Repeat steps 3-5 for each property you want to set for the selected form or control.

Note	To set a property that is shared by more than one control on a form, select the controls that share the property you want to change.  Change the property in the Properties window to affect all selected controls.

To set form or control properties at run time

Place a reference to the property (object.property) on the left side of an assignment statement.  For example:

Text1.Text = "Your Name"


See Also

Help:

Properties List

Learning Visual Basic:

Creating an Application

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Accessing Screen Properties

See Also

Like forms and controls, the Screen object has a set of predefined properties.  Unlike form and control properties, however, Screen properties are available only at run time and thus cannot be set in the Properties window.  You can access and manipulate Screen properties only in code at run time.  Screen properties are global for the current project.

To access a Screen property through code

Use the syntax Screen.propertyname [image] for example, Screen.Width.

The Screen properties are:

ActiveControl

ActiveForm

FontCount

Fonts

Height

MousePointer

TwipsPerPixelX

TwipsPerPixelY

Width


See Also

Help:

App Object

Clipboard Object

Debug Object

Printer Object

Screen Object

Setting Form and Control Properties


Setting Colors

See Also

You can set background and foreground colors for forms and controls using the Color palette.

To set colors with the Color palette

1.	From the Window menu, choose Color Palette.

The box on the left side of the palette displays the currently selected colors [image] the foreground color in the inner box and the background color in the outer box.

2.	Select the form or control whose color you want to change.

3.	To change the foreground color for the selected object, click the inner box, then click a color on the color box; to change the background color for the selected object, click the outer box, then click a color on the color box.

To set colors in the Properties window

1.	From the Properties window, select the color property you want to set either by clicking the property name in the Property list or by pressing Ctrl+Shift+ the first letter of the property name you want to select.

Visual Basic displays the current color setting in the Settings box, and the down arrow to the right of the Settings box changes into a button with three dots.

2.	Click the button with three dots or double-click the color property name.

3.	Click the color you want from the available choices.

Note	You can set normal RGB colors with the BackColor and ForeColor properties or in code using the RGB or QBColor functions in code.

If you specify colors using the system color constants from the CONSTANT.TXT file, Visual Basic substitutes the color-scheme choices the user has made in the Control Panel settings.


See Also

Help:

Creating Custom Colors


Creating Custom Colors

See Also

You can create custom colors using the Color palette.

To add a color to the Color palette

1.	From the Window menu, choose Color Palette.

2.	Click the Custom Colors button.

Visual Basic displays a row of color boxes at the bottom of the Color palette that you can use to set custom colors.

3.	Select a blank color box.

4.	Click the Define Colors button.

Visual Basic displays a dialog box with various color settings.

5.	Click anywhere in the large box to select a color.

6.	Click the bar at the right of the box to select the color you want, or click and drag the arrow displayed at the right of the bar to vary the shade and brightness of the color.

Visual Basic displays the selected color in the Color display box.

7.	Optional:  To fine-tune the color, adjust the numbers for the red, green, and blue color elements.

8.	Choose Add Color to add the color to the Color palette.

Note	Custom colors you have created are among the choices available from the Settings box of the Properties window.


See Also

Help:

Setting Colors


Guidelines for Entering and Editing Code

See Also

You enter and edit code in the Code window.  The Code window has automatic formatting and syntax checking capabilities built in.  If the syntax checker is turned on, Visual Basic displays a message when you enter code that has a syntax error.

Using the Code Window

To enter code, click the Code window and start typing.

To correct mistakes as you type, press Backspace.

To delete text, select it and press Del.

To move the insertion point, click where you want the insertion point to be, or use the Arrow keys.

To indent text, select the line or lines you want to indent, and press Tab.  To remove an indent, press Shift+Tab.

To switch between insert mode and overtype mode, press Ins.

To enter a comment in your code, start the comment with an apostrophe ( ' ).

To complete a Visual Basic statement, press Enter at the end of the line or move the pointer off the line.

To write multiple statements on one line, use a colon (:) as a separator.  For example:  For I = 1 to 100: A(I) = I: Next I

To view two procedures at a time, split the window by moving the split bar down the side of the Code window.

To accept arguments in a procedure, separate the arguments by commas if there is more than one, and enclose all the arguments in parentheses following the name of the procedure.  For example, Sub IncrementXY(X, Y).

To pass arguments to a procedure, separate the arguments by commas if there is more than one, following the name of the procedure being called.  For example, IncrementXY X, Y.  Enclose the arguments in parentheses following the procedure name only if the the Call keyword is being used before the procedure name.  For example, Call IncrementXY(X, Y).

To get Help on syntax for Visual Basic functions, statements, properties, events, or methods while working in the Code window, type or select the keyword, the property, event, or method name, and press F1.

Declarations and Variables

To make an assignment of one variable to another, use the syntax destination = source.

To name a variable, begin the name with a letter and use no more than 40 letters and numbers.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Creating a General Procedure

Data Types

Entering Declarations in Code

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 6, "Programming Fundamentals"

Chapter 7, "Variables, Constants, and Data Types"


Attaching an Event Procedure to a Form or Control

See Also

The code you attach to a form or control is called an event procedure.  Every form and control has a set of predefined events that it can recognize.  You attach event procedures only for events to which you want a form or control to respond.

To attach an event procedure to a form or control

1.	Double-click a blank part of the form to open the form's Code window.  To attach code to a control, double-click the control.

2.	In the Procedure box, select the event to which you want to attach code.

3.	Enter the code you want in the template provided, following guidelines for entering and editing code and declarations.

4.	Repeat steps 2 and 3 as necessary to attach additional event procedures to the item.

Syntax

Use this syntax when writing an event procedure:

Sub ItemName_EventName (arguments)

local variable and constant definitions

statements

End Sub

Note	When attaching an event procedure, you can also select a form or control from the Object box in the Code window.  The information displayed in the Procedure box then changes to reflect the predefined events for the object you have selected.  Bold text in the Procedure box indicates event procedures for which you have written code.

Instead of using the template provided for you by Visual Basic, you can also create a new procedure by typing Sub ProcedureName in the Code window.

If you change the Name property of a control after attaching a procedure to it, you must also change the name of the procedure to match the name of the control.  Otherwise, Visual Basic won't be able to match the control to the procedure.  You can find the procedure by selecting (general) from the Code window's Object box and then selecting the procedure from the Procedure box.

For a list of the events that apply to forms and each type of control, see the topics under the Properties, Events, and Programming Language indexes.  For a list of all Visual Basic events, see the Events index.


See Also

Help:

Creating a General Procedure

Learning Visual Basic:

Writing Event-Driven Programs

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"


Entering Declarations in Code

See Also

Declarations are nonexecutable code statements that name external procedures, constants or variables and define their attributes (such as data type).  You write declarations for forms or modules.  To enter module-level declarations, go to the Declarations section of the form or module.  To enter global declarations, go to the Declarations section of a module and use the Global statement for constants and variables.

You can also enter procedure-level declarations.  For whatever code level and technique you use to declare a variable or constant, specific scoping rules may apply.  For details on scoping declarations, see Chapter 7, "Variables, Constants, and Data Types," in the Programmer's Guide.

To open the Declarations section for a form

1.	Double-click the form to open the Code window.

2.	In the Object box, select (General).

The Procedure box automatically displays (Declarations).

3.	Enter the declarations you want, following the guidelines for entering and editing code.

To open the Declarations section for a module

1.	In the Project window, select the module you want to open and click the View Code button.

2.	In the Procedure box, select (Declarations).

3.	Enter the declarations you want.

Note	Visual Basic comes with the file CONSTANT.TXT.  This file specifies system defaults such as colors, key codes, and defaults for properties and events.  You can load CONSTANT.TXT into any module and modify it to your specifications.


See Also

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application".

Chapter 7, "Variables, Constants, and Data Types"


Creating a General Procedure

See Also

A general procedure tells the application how to perform a specific task.  Once the procedure is defined, it must be explicitly invoked by the application.  By contrast, an event procedure remains idle until called upon to respond to events caused by the user or triggered by the system.  You can place a general procedure in either form code or in a module.  General procedures in a form can be accessed only from within that form; general procedures in a module can be accessed from any form or module in your application.  Using general procedures can help divide complex application code into more manageable units.

To create a general procedure

1.	Open the Code window for the form or module for which you want to write the procedure.

2.	From the View menu, choose New Procedure.

3.	In the text box, type a name for the procedure.

4.	Select Sub to create a Sub procedure or Function to create a Function procedure.

Note that a Function procedure returns a value and a Sub procedure does not.

5.	Choose OK.

Visual Basic sets up a template so you can enter code for the general procedure.

Note	You can also create a new procedure by typing Sub ProcedureName or Function ProcedureName in the Code window.

Syntax

Use this general syntax when writing a Sub procedure:

Sub ProcedureName (arguments)

local variable and constant declarations

statements

End Sub

Use this syntax when writing a Function procedure:

Function ProcedureName (arguments) As datatype

local variable and constant declarations

statements

ProcedureName = return value

End Function

Use general procedures for:

Sharing code among controls on one form.  Write a general procedure in form code and attach an event procedure to each control that invokes the general procedure.

Sharing code among multiple forms.  Create a module and write the shared code there as a general procedure.  For each form or control you want to share the code, attach an event procedure that calls the general procedure.

If you have too much code in a module you may exceed memory limitations.  It may help if you create one or more modules and offload code by attaching to the form or its controls short event procedures that call general procedures in the module(s).  Place global declarations in any module.

Multiple-form application startup.  Create a module and write a general procedure called Main for your startup routine.


See Also

Help:

Guidelines for Entering and Editing Code

Programmer's Guide:

Chapter 6, "Programming Fundamentals"

Chapter 7, "Variables, Constants, and Data Types""


Turning Syntax Checking On or Off

See Also

The Visual Basic Code window includes a syntax-checking feature that:

Checks each line of code for syntax errors (such as a misspelled keyword or missing separator) as you enter it, and alerts you if there are errors.

Translates the code to an internal form if the syntax is correct, which speeds the transition to run mode.

This feature is turned on when you first start up Visual Basic, but you can turn it off if you prefer to write all your code without being alerted to errors as they occur.

To turn syntax checking on or off

1.	From the Options menu, choose Environment.

2.	Select Syntax Checking.

3.	In the Setting box, select either Yes or No to enable or disable syntax checking.

Note	When you make a change to the Environment options, those changes are saved in the Visual Basic initialization file (VB.INI).


See Also

Help:

Guidelines for Entering and Editing Code


Using Example Code from Online Help

See Also

You can copy example code from online Help, paste it into the current Code window, and then edit the code to fit your needs.  Code examples are provided in the Programming Language, Properties, and Events topics.

To copy and paste example code from Help into your code

1.	Find the topic you want.

2.	Click the word Example in the non-scrolling region of the topic to jump to the code sample.

3.	In the secondary window that contains the code sample, choose Copy.

4.	In the Copy window, select the code you want to copy to the Code window and choose the Copy button.

5.	In the Code window, click where you want to insert the example code.

6.	From Visual Basic's Edit menu, choose Paste (Ctrl+V).

Note	After copying example code from Help, you may need to modify variables, constants, and references to form and control names to fit your application.  Be sure that you add an apostrophe ( ' ) at the beginning of each comment, especially if it wraps to a second line.  Failure to do so may prevent the code from executing.


See Also

Help:

Guidelines for Entering and Editing Code

Replacing Text in Code

Programmer's Guide:

Chapter 1, "Introduction"


Importing a Text File into Code

See Also

You can import a text file containing code into the current project and use it in your code.

To import a text file into the Code window

1.	From the File menu, choose Load Text.

2.	From the Files box, select the file you want to import.

3.	Choose Replace to replace all code in the current Code window with the imported text; choose Merge to add the text at the insertion point; or choose New to open a new module and load the text there.

Note	For compatibility with Microsoft Windows, Visual Basic uses the character codes in the ANSI character set, instead of the ASCII character set.


See Also

Help:

Guidelines for Entering and Editing Code

Using Example Code from Online Help


Finding a Procedure

See Also

To find a procedure in a Code window

1.	From the Window menu, choose Procedures (F2).

2.	From the Modules list box, choose the module containing the procedure you want to find.

3.	Select the procedure you want either by scrolling through the entries in the Procedures list box and clicking the procedure name, or by pressing the keyboard key for the first letter of the procedure name.  If you press the first letter key and the procedure you want is not selected, continue to press the key until the procedure you want is selected.

4.	Choose OK.

The procedure you have chosen is displayed in the Code window.

To find the next or previous procedure in a Code window

From the View menu, choose Next Procedure or Previous Procedure.

Keyboard Shortcuts

Press	To

Ctrl+Down Arrow	Display the next procedure.

Ctrl+Up Arrow	Display the previous procedure.

Page Down	Page down through the procedures in your code.

Page Up	Page back up through the procedures in your code.

F2	Display View Procedures dialog.


See Also

Help:

Replacing Text in Code

Searching for Text in Code


Searching for Text in Code

See Also

To search for specific text in the Code window

1.	From the Edit menu, choose Find (Ctrl+F).

2.	In the Find What text box, type the text you want to search for.  If any text is selected when you choose the command, this text is displayed in the text box.  If no text is selected, the word at the current insertion point is displayed.

3.	Select a Search option button to specify where to look for the text:

Current Procedure searches in the current procedure only.

Current Module searches in the active module only.

All Modules searches all the code in your project, including all forms.

4.	To set limits on the search, select the Match Whole Word Only check box to search only for the complete word by itself, and not as part of another word.  Select the Use Pattern Matching check box to search using pattern matching characters.

5.	Choose OK.

Visual Basic finds the first occurrence of the text.

6.	To find the next or previous occurrence of the text, choose Find Next or Find Previous from the Edit menu.

Keyboard Shortcuts

Press	To

Ctrl+F	Find: display Find dialog box.

F3	Find Next: repeat text search down through your code.

Shift+F3	Find Previous: repeat text search up through your code.


See Also

Help:

Finding a Procedure

Replacing Text in Code


Replacing Text in Code

See Also

To replace text in the Code window

1.	From the Edit menu, choose Replace (Ctrl+R).

2.	In the Find What text box, type the text you want to search for.  If any text is selected when you choose the command, this text is displayed here.  If no text is selected, the word at the current insertion point is displayed.

3.	In the Replace With text box, type the replacement text.

4.	Select a Search option button to specify where to look for the text:

Current Procedure searches in the current procedure only.

Current Module searches in the active module only.

All Modules searches all the code in your project, including all forms.

5.	Select Syntax Checking On if you want the syntax checked after each replacement is made.

6.	To set limits on the search, select the Match Whole Word Only check box to search only for the complete word by itself, and not as part of another word.  Select the Use Pattern Matching check box to search using pattern matching characters.

7.	Choose Verify if you want to confirm before changing each occurrence of the text, or choose Replace All to change all occurrences of the search text automatically.


See Also

Help:

Finding a Procedure

Searching for Text in Code


Splitting a Code Window Into Panes

You can split the Code window horizontally into two panes to view different code segments for a form or module at the same time.  Each pane scrolls separately, both horizontally and vertically.  The Procedure and Object box options refer to the pane that has the focus.  Code changes are immediately reflected in both panes.

To split the Code window into panes

Under the window's title bar, click and drag the split bar down.

To remove a split from the Code window

Click and drag the split bar back up to the title bar.


Saving Your Work

See Also

In Visual Basic, you can save entire projects as well as specific forms and modules.

To save a new or existing project

1.	From the File menu, choose Save Project, or use the toolbar shortcut:

If you have not previously saved the project, Visual Basic displays a dialog box in which you name and save the project.

2.	In the File Name text box, type a project name.

Unless you type a different file-name extension, Visual Basic automatically adds the extension .MAK.

3.	Choose OK.

If you have unsaved forms or modules in the project, Visual Basic prompts you to save them as well.

To save a new form or module

1.	Click the Form window for the form you want to save

or

Click the Code window for the module you want to save

or

Select the form or module you want to save in the Project window.

2.	From the File menu, choose Save File As (Ctrl+A).

3.	In the File Name text box, type a name for the form or module.

Unless you type a different file-name extension, Visual Basic automatically adds the extension .FRM for forms and .BAS for modules.

4.	Select Save As Text if you want the form or module saved as text.

5.	Choose OK.

To save changes to an existing form or module

1.	Click the form or module you want to save.

or

Select the form or module you want to save in the Project window.

2.	From the File menu, choose Save File (Ctrl+S).

To save code as a text file

1.	Click the module or form code you want to save.

2.	From the File menu, choose Save Text.

3.	In the File Name text box, type a name for the module.

Unless you type a different file-name extension, Visual Basic automatically adds the extension .TXT.

4.	Choose OK.


See Also

Help:

Importing a Text File into Code

Learning Visual Basic:

Creating an Application

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 5, "Managing Projects"


Debugging Checklist

See Also

There are three types of errors you may encounter as you run your application:

Compile errors [image] occur as a result of code that is incorrectly constructed.  You may have an incorrectly matched control structure, such as a Next statement without a corresponding For statement, or programming mistakes that violate the rules of Basic, such as a misspelled word, a missing separator, or a type mismatch.

Compile errors include syntax errors, which are errors in the grammar or punctuation recognized by Visual Basic.  Examples of syntax errors include passing an incorrect number of arguments to an intrinsic function or forgetting to match parentheses.

Run-time errors [image] occur after the application starts to execute.  Examples of run-time errors include attempting an illegal operation, such as writing to a file that doesn't exist, or dividing by zero.

Logical errors [image] the program doesn't perform as intended, and produces incorrect results.

Debugging is a process by which you find and resolve errors in your code.  To debug code in Visual Basic, consider the ideas suggested below.  These techniques can also be applied in different sequences.

1.	Print the code, if you find it easier to read code on paper instead of online.

2.	Run the application to find trouble spots:

From the Run menu, choose Start (F5) to begin running the application.

Run until an error stops execution, or halt execution manually when you suspect an error by choosing Break from the Run menu (Ctrl+Break).

Resolve all compile errors and run-time errors.

From the Run menu, choose Continue (F5) to continue running the application.

3.	Use debugging tools and techniques to isolate bugs and to monitor code flow:

Set breakpoints to halt execution at certain points to look for problems such as incorrect variable types, mixups in variable names, flaws in logical comparisons, endless loops, garbled output, problems with arrays, and so on.  You can also set breakpoints to monitor code flow or examine information in the current state.

Add a watch expression at design time or while in break mode to allow you to monitor the value of a particular expression as your code execution progresses.

Single step (F8) or procedure step (Shift+F8) through your code to trace through the application as it's running.

Use the Debug window to test individual lines of code or procedures, or to change values.

Enter break mode and choose Calls (Ctrl+L) from the Debug window to see where your code is currently executing and trace the path showing how it got there.

4.	Try out bug fixes and then make edits:

Test individual lines of new or debugged code in the Debug window.

Search and replace code for all occurrences of an error, checking other procedures, forms, or modules with related code.

From the Run menu, choose Restart (Shift+F5) to reset application variables and properties and restart the application from the beginning.


See Also

Help:

Continuing Execution

Ending Execution

Finding a Procedure

Guidelines for Entering and Editing Code

Halting Execution

Restarting Execution

Starting Execution

Learning Visual Basic

Debugging Your Application

Programmer's Guide:

Chapter 9, "Debugging"


Starting Execution

See Also

One way to test your application is to run it and work with it as a user would.

To start execution

1.	From the Run menu, choose Start (F5), or use the toolbar shortcut:

2.	Test your application by using each control on each form.

The program ends when all forms are closed and no code is executing, when Visual Basic encounters an End statement in your code, or when you choose the End command from the Run menu or use the toolbar shortcut: .

If your application doesn't run, it may be because:

Visual Basic encounters a syntax error or some other compile error in your code.

Visual Basic encounters a logic error in your code, which may result in a compile or run-time error.

To get context-sensitive Help, press F1 while an error message is on the screen.  Consider the suggestions provided to correct the error before you try to execute the application again.


See Also

Help:

Continuing Execution

Debugging Checklist

Ending Execution

Halting Execution

Restarting Execution

Specifying a Startup Form

Learning Visual Basic

Creating an Application

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 9, "Debugging"


Halting Execution

See Also

As you run your application, it may halt for one of the following reasons:

An untrapped run-time error occurs.

Visual Basic encounters a breakpoint you set previously.

Visual Basic encounters a watch expression that you have set to break if its value changes or becomes true.

Visual Basic encounters a Stop statement or an End statement in your code.

You halt execution manually at a given point.

To halt execution manually

From the Run menu, choose Break (Ctrl+Break), or use the toolbar shortcut:

To continue execution when your application has halted

From the Run menu, choose Continue (F5), or use the toolbar shortcut:

or

From the Debug menu, choose Single Step (F8) or Procedure Step (Shift +F8).


See Also

Help:

Continuing Execution

Debugging Checklist

Ending Execution

Restarting Execution

Starting Execution

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 9, "Debugging"


Continuing Execution

See Also

As you run your application, it may halt for one of the following reasons:

An untrapped run-time error occurs.

Visual Basic encounters a breakpoint you set previously.

Visual Basic encounters a watch expression that you have set to break if its value changes or becomes true.

Visual Basic encounters a Stop statement or an End statement in your code.

You halt execution manually at a given point.

To continue execution when your application has halted (in all cases except after an End statement)

From the Run menu, choose Continue (F5), or use the toolbar shortcut:

or

From the Debug menu, choose Single Step (F8) or Procedure Step (Shift +F8).

Note	While in break mode, the edits you make to your code may cause syntax errors or other compile errors.  Visual Basic evaluates each new line of code before making the change and alerts you about errors in your code.  If you make a change that prevents execution from continuing, Visual Basic displays an alert with the option of canceling the change or of proceeding.  If you cancel the change, Visual Basic reverses the change by either deleting the incorrect line of new code or restoring the previous state of an old line of code.  If you choose to proceed, Visual Basic ends execution and returns to design mode.

You may want to change the sequence of your code with the Set Next Statement command (Debug Menu) to either rerun the changed statement or to bypass it.


See Also

Help:

Debugging Checklist

Ending Execution

Executing a Specific Statement

Restarting Execution

Starting Execution

Programmer's Guide:

Chapter 9, "Debugging"


Restarting Execution

See Also

You can restart execution of your application from break mode.  Restarting an application returns it to a newly initialized state, resetting all variables and removing any suspended procedures from memory.

To restart execution

From the Run menu, choose Restart (Shift+F5).

Visual Basic returns your application to a newly initialized state and starts running the application from the beginning.


See Also

Help:

Continuing Execution

Debugging Checklist

Ending Execution

Halting Execution

Starting Execution

Programmer's Guide:

Chapter 9, "Debugging"


Ending Execution

See Also

To end execution

From the Run menu, choose End, or use the toolbar shortcut:

or

Unload the last remaining form in the application.


See Also

Help:

Halting Execution

Restarting Execution

Starting Execution

Programmer's Guide:

Chapter 9, "Debugging"


Executing a Specific Statement

See Also

While execution of your code is halted, you can control the execution sequence of statements within a procedure.  You can resume execution at a statement you choose without executing any intervening code.

To set the next statement to be executed

1.	In the Code window, position the insertion point anywhere within the statement.

2.	From the Debug menu, choose Set Next Statement.

Note	You can skip only to statements within the same procedure.

During run time you can use a GoTo statement to branch to a specified line within a procedure.

Used in combination with single stepping, executing specific statements with the Set Next Statement command enables you to step through procedures one statement at a time, and to closely examine your code.  It's also helpful for correcting or avoiding run-time error conditions.


See Also

Help:

Debugging Checklist

Finding a Procedure

Tracing Execution

Programmer's Guide:

Chapter 9, "Debugging"


Tracing Execution

See Also

Tracing execution is useful in Visual Basic because in event-driven programming, it may not be obvious which statement is executed first.  Use these techniques to trace the execution of code:

Single stepping [image] tracing through each line of the procedure.  This shows you the effect of each statement on variables.

Procedure stepping [image] executing each procedure as if it were a single statement.  Use this instead of single stepping to step across procedure calls rather than into the called procedure.

To trace execution from the current statement

From the Debug menu, choose Single Step (F8), or use the toolbar shortcut [image] to execute code one line at a time.

From the Debug menu, choose Procedure Step (Shift+F8), or use the toolbar shortcut [image] to step across procedure calls.

To trace execution from the beginning of the program in break mode or run time

1.	From the Run menu, choose End, or use the toolbar shortcut:

Visual Basic resets all variables, removes any suspended procedures from memory, and returns to design time.

2.	From the Debug menu, choose Single Step (F8); or choose Procedure Step (Shift+F8).

The program runs until the first event procedure or Sub Main begins executing.

Note	You can also set a breakpoint or watch expression within a procedure before you start running the application.  When the application halts at the breakpoint, trace from that point.


See Also

Help:

Debugging Checklist

Finding a Procedure

Programmer's Guide:

Chapter 9, "Debugging"


Setting and Clearing Breakpoints

See Also

A breakpoint is a line in a program that you set to interrupt normal execution.  You set breakpoints to halt execution at specific statements in a procedure [image] for example, where you suspect problems may exist.  You clear breakpoints when you no longer need them to halt execution.

To set a breakpoint

1.	Position the insertion point anywhere in a line of the procedure where you want execution to halt.

2.	From the Debug menu, choose Toggle Breakpoint (F9), or use the toolbar shortcut:

Visual Basic adds the breakpoint and highlights the line using the breakpoint color set in the Environment Options dialog box.

3.	If the application is not running, choose Start (F5) from the Run menu, or use the toolbar shortcut: .  If the application halted during execution, choose Continue (F5) to continue through the program; or choose Restart (Shift+F5) from the Run menu to reset variables and run the application from the beginning.

Visual Basic halts execution whenever it encounters a breakpoint.

To clear a breakpoint

1.	Position the insertion point anywhere on a line of the procedure containing the breakpoint.

2.	From the Debug menu, choose Toggle Breakpoint (F9), or use the toolbar shortcut:

Visual Basic clears the breakpoint and removes the highlighting.

To clear all breakpoints in the application

From the Debug menu, choose Clear All Breakpoints.

Visual Basic clears all breakpoints in the application.

Note	Breakpoints set in code are not saved when you save forms and modules.  Closing a project or quitting Visual Basic automatically clears them.  Breakpoints also have no effect when creating an executable file since they are not saved.  A Stop statement, however, halts an executable file.

If you set a breakpoint on a line that contains several statements separated by colons (:), the break will always occur at the first statement on the line.


See Also

Help:

Adding, Editing, and Deleting Watch Expressions

Debugging Checklist

Programmer's Guide:

Chapter 9, "Debugging"


Adding, Editing, and Deleting Watch Expressions

See Also

A watch expression is an expression you define which Visual Basic then monitors for you.  When your application enters break mode, the watch expressions you have selected appear in the Watch pane of the Debug window where you can observe their values.  You can delete them once you are satisfied that the results are as you expect.

To add a watch expression

1.	From the Debug menu, choose Add Watch.

2.	Enter the expression you want evaluated in the Expression box.

3.	Click an option button in the Context group to select the range for when the expression will be evaluated.

4.	Click an option button in the Watch Type group to select how Visual Basic should respond to the watch expression.

5.	Choose OK.

To edit a watch expression

1.	From the Debug menu, choose Edit Watch (Ctrl+W).

2.	Select the watch expression you want to edit from the Current Expressions list.

3.	Choose Edit.

4.	Make the changes you want to the expression, the context, and the watch type.

5.	Choose OK.

To delete a watch expression

1.	From the Debug menu, choose Edit Watch (Ctrl+W).

2.	Select the watch expression you want to delete from the Current Expressions list, if you want to delete only one watch expression.

3.	Click Delete to delete a single watch expression or click Delete All to delete all the current watch expressions.

Note	Watch expressions are not saved when you save forms and modules.  Closing a project or quitting Visual Basic automatically clears them.


See Also

Help:

Debugging Checklist

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Using Instant Watch

See Also

While in break mode, you may want to check the current value of some variable or expression for which you have not defined a watch expression.  Do this using the Instant Watch command.

To display an instant watch

1.	Highlight an expression in either the Code window or the Immediate pane of the Debug window.

2.	From the Debug menu, choose Instant Watch (Shift+F9), or use the toolbar shortcut:

The Instant Watch dialog box displays the current value of the expression you selected.

3.	If you want to add a watch expression based on the expression in the Instant Watch dialog, click the Add Watch button.


See Also

Help:

Adding, Editing, and Deleting Watch Expressions

Debugging Checklist

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Using the Debug Window

See Also

To execute code in the Debug window while in break mode

1.	Type a line of code in the Debug window.

2.	Press Enter to execute the statement.

Use the Debug window to:

Test problematic or newly written code.

Query or change the value of a variable while running an application.  While execution is halted, assign the variable a new value as you would in code.

Query or change a property value while running an application.

Simulate a run-time error.  To see which error-message dialog box is associated with a given error code, type:

error errornumber

Call procedures as you would in code.

View debugging output while the program is running.

Note	Debug window statements are executed in a context [image] that is, as if they are entered in a specific form or module.  This context appears in the title bar of the Debug window.

If you need help on syntax for functions, statements, properties, events, or methods while working in the Debug window, select the keyword or the property, event, or method name, and press F1.

While in the Debug window, you can do most of the things you do in the Code window, but statements in the Debug window are not saved with the project.  If you want to save such code, copy or cut it and then paste it into the Code window.


See Also

Help:

Debugging Checklist

Programmer's Guide:

Chapter 9, "Debugging"


Specifying a Startup Form

See Also

 An application does not have to start up with the first form in the project; you can start your application with any form or a Sub Main procedure in a module.

To specify a startup form

1.	From the Options menu, choose Project.

Visual Basic displays a dialog box.

2.	Select Set Startup Form.

3.	In the Setting box, select the form you want to start your application.

4.	Choose OK.

Instead of loading a form, Visual Basic can invoke a procedure to start an application.

To specify a startup procedure

1.	Write a general Sub procedure called Main and save it in a module.

2.	From the Options menu, choose Project.

Visual Basic displays a dialog box.

3.	Select Set Startup Form.

4.	In the Project Options Setting box, choose Sub Main.

5.	Choose OK.

When the project starts execution, Sub Main is called immediately.


See Also

Programmer's Guide:

Chapter 5, "Managing Projects"


Assigning an Icon to a Form

See Also

You can assign a unique icon to any form that the user can minimize at run time.  If you do not assign an icon to a form, the form.ico file in the \icons\misc directory is the default.

To assign an icon to a form with the Properties window

1.	Click a blank part of the form to select it.

2.	In the Properties window, select Icon.

The down arrow to the right of the Settings box changes into a button with three dots.

3.	Click the button with three dots.

Visual Basic displays the Load Icon dialog box.

4.	Type or select the name of the icon you want to use.

5.	Choose OK.

Note	You can assign a unique icon to any form that the user can minimize at run time.  A unique icon can provide the user with a visual cue as to the function of a form or application.  Visual Basic's Icon Library is a good source for icons.


See Also

Help:

Setting Form and Control Properties

Specifying a Startup Form

Using Icons

Programmer's Guide:

Chapter 5, "Managing Projects"


Specifying Access Keys

See Also

An access key gives the user quick keyboard access to a menu, command, or control.  Unlike shortcut keys, access keys do not execute commands when pressed.  At design time, you designate a letter in the caption to be the access key.  At run time, this letter is underlined, and the user can access the menu or command by pressing Alt plus the letter.

To assign an access key to a control with the Properties window

1.	Click the control to select it.

2.	From the Properties window, select Caption.

3.	Type the caption in the Settings box.  Include an ampersand (&) in the caption immediately preceding the character you want to appear underlined at run time.  For example, if you type "&Add," the caption on the control appears as Add, and the access key is Alt+A.

4.	Click the Enter button.

To assign an access key to a menu or command with the Menu Design window

1.	Click the form with the menu bar.

2.	From the Window menu, choose Menu Design (Ctrl+M).

3.	In the Caption text box, type the menu name as you want it displayed on the menu bar.  Include an ampersand (&) immediately preceding the character you want to appear underlined at run time.  For example, if you type "Fi&le" the caption on the control appears as File, and the access key is Alt+L.

4.	Choose OK.


See Also

Help:

Creating a Menu Bar

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"


Setting Tab Order

See Also

By default, Visual Basic assigns tab order to controls in the order you draw them on a form.  Each new control is placed last in the tab order.  To allow you to control the order that controls gain focus in your application, you can change the tab order at design time with the Properties window, or at run time through code.

To change tab order at design time

1.	Click a control to select it.

2.	From the Properties window, select TabIndex.

Visual Basic displays the current tab position in the Settings box.

3.	Type the number for the tab order position you want the control to have.

4.	Click the Enter button.

You can test the tab order at design time by pressing Tab.

To enable or disable a tab stop at design time

1.	Click a control to select it.

2.	From the Properties window, select TabStop.

Visual Basic displays the current Boolean value in the Settings box.

3.	Select True to designate the control as a tab stop, or select False to bypass the control in the tab order.

4.	Click the Enter button.

Note	When you change a control's tab order position, Visual Basic automatically renumbers the tab order positions of other controls to reflect insertions and deletions.

A control whose TabStop property has been set to False maintains its position in the actual tab order as set by the TabIndex property, even though the control is skipped when you cycle through the controls with the Tab key.


See Also

Help:

TabIndex Property

TabStop Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Creating a DDE Source or Destination Link

See Also

You can create data links between a Visual Basic application and other applications that support DDE.  The application that initiates the DDE conversation is the destination.  The application that responds to the destination is the source.  You use these links to get information from, or supply information to, another application.

To create a destination link

1.	In the source application, select the data item you want to link.

2.	From the source application's Edit menu, choose Copy.

3.	In your Visual Basic application, select the control (text box, label, or picture box) you want to receive the data.

4.	From Visual Basic's Edit menu, choose Paste Link.

If the link is successful, the control displays the data selected from the source application.

To create a source link

1.	In your Visual Basic application, select the form or control that contains the data you want to supply.

2.	From Visual Basic's Edit menu, choose Copy (Ctrl+C).

3.	In the destination application, select the destination for the data.

4.	From the destination application's Edit menu, choose Paste Link.

If the link is successful, the contents of the control are displayed in the destination application.

Note	The Paste Link command establishes an automatic link [image] a change in the source's data will automatically cause an update in the destination's data.  When an application with an automatic link is opened, a DDE conversation with the source application is automatically reestablished.  In contrast, a manual link requires user action to establish a DDE conversation and to update data.  Use the LinkMode property to specify an Automatic (1), Manual (2), or Notify (3) link for the destination control.


See Also

Help:

LinkItem Property

LinkRequest Method

LinkTimeout Property

LinkTopic Property

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


array

A fixed-size set of sequentially indexed elements having the same data type.  Each element of an array has a unique index number that identifies it.  Changes made to an element of an array do not affect the other elements.


client area

The area in an MDI form which is used to display MDI child forms.  The client area does not include the MDI form's title bar, border, menu bar, or aligned controls placed in the MDI form.


collection

An ordered set of similarly typed objects.  Collection elements are ordered numerically from zero to Count -1.  An object's position in the collection may change whenever a change occurs in the collection.  This makes the position of any specific object in the collection unpredictable.  This characteristic distinguishes a collection from an array, which is similar to a collection, but whose member objects maintain their position in the array unless they are explicitly changed.


comparison operator

Comparison operators, also known as relational operators, compare two expressions.  For example, =, <, >, and <> are comparison operators.


compile time

The point at which a program is compiled.  Compile errors are caused by programming mistakes such as misspelled words, missing separators, or for example, a Next statement used without a corresponding For statement.


data type

The characteristic of a variable that determines its attributes and the kind of data it can hold.  Fundamental data types include Variant (the default), Integer, Long, Single, Double, Currency, and String.  You can combine fundamental data types into user-defined types using the Type statement.  You can create arrays of fundamental or user-defined types using the Dim statement.  You can include both arrays and user-defined types within other user-defined types.


destination

When two or more programs that support dynamic data exchange (DDE) are running simultaneously, the program designated to receive the information and commands is the destination.


Empty

An uninitialized Variant that is 0 in a numeric context or zero-length in a string context.


position indicator

An indicator that shows the position of the selected form or control relative to its container.  For forms, position is always shown in twips.  For controls, position is shown in the units of measure specified in the ScaleMode property of the container.


size indicator

The indicator that shows the size of a selected form or control.  For forms, size is always shown in twips.  For controls, size is shown in the units of measure specified in the ScaleMode property of the container.


image control

A graphical control you can use to display a picture.


instance

Any one of a set of objects sharing the same type.  For example, multiple instances of a form type share the same code and are loaded with the same controls with which the form type was designed.  During run time, the individual properties of controls on each form instance can be set to different values.


MDI child

In a multiple-document interface (MDI) application, the forms contained within the MDI form are child forms.


MDI form

A window making up the background of a multiple-document interface (MDI) application.  The MDI form is used as the container for any MDI child forms in the application.


module variable

A variable declared in the Declarations section of a form or code module and visible in all procedures in the module.  It is also called a module-level variable.


Null

A variable having VarType 1 (no valid characters or values).  A Null variable is different from both a variable with a value of zero and an Empty variable (VarType 0).


numeric expression

A sequence of characters that can be interpreted as a numeric value.  Also, any combination of variables, constants, functions, and operators that an application can evaluate to yield a number.


object data type

Object types include the generic types Form and Control, and specific types MDIForm, user-defined form types, and standard and custom-control types.  A user-defined form type corresponds to its Name property.  A custom-control type corresponds to its class name.  The standard control types include CheckBox, ComboBox, CommandButton, DirListBox, DriveListBox, FileListBox, Frame, HScrollBar, Image, Label, Line, ListBox, OptionButton, PictureBox, Shape, TextBox, Timer, and VScrollBar.  The grid and OLE client custom controls have the types Grid and OLEClient, respectively.  Object-type specifications are keywords but not reserved words.


seed

An initial value used to generate pseudo-random numbers.  For example, the Randomize statement accepts a seed number used by the Rnd function to create unique pseudo-random number sequences.


system modal

Describes a window or dialog box that requires the user to take some action.  This term means the same as "modal" except that the focus cannot switch to any other form or dialog in any running applications.


sort order

A sequencing principle used to order data [image] for example, alphabetic, numeric, ascending, descending, and so on.


source

When two or more programs that support dynamic data exchange (DDE) are running simultaneously, the program designated to send the information and commands is the source.


string comparison

A comparison of two sequences of characters.  Comparisons can be either binary or text.  Binary comparisons are case-sensitive; text comparisons are not case-sensitive.


string expression

Any expression that evaluates to a sequence of continguous characters.  Elements of the expression may include a function that returns a string; a string literal; a function that returns a Variant of VarType 8 (string); or a string constant or string variable.


two's complement

A type of base-2 notation used to represent positive and negative in which negative values are formed by complementing all bits and adding 1 to the result.  Complementing is done by changing all 1s to 0, and all 0s to 1.


type-declaration character

One of the characters (!, #, $, %, @, or &) that can be appended to a variable name to specify its data type.  Undeclared variables lacking type-declaration characters have a default Variant type, unless a Deftype statement is present in the form or module.


valid date separators

Characters used to separate the day, month, and year when date values are formatted.  The characters are specified by settings in the International section of the Control Panel or by the Format, Format& functions.


VarType

The VarType function returns a value that provides information about the type of data stored in a Variant.

Symbolic constant	Value	Meaning
V_EMPTY	0	Empty
V_NULL	1	Null
V_INTEGER	2	Integer
V_LONG	3	Long
V_SINGLE	4	Single
V_DOUBLE	5	Double
V_CURRENCY	6	Currency
V_DATE	7	Date
V_STRING	8	String


variable naming

A variable is a location in memory containing a value that can change as an application runs.  Each variable has a unique name that identifies it within its level of scope.  Variable names must be limited to 40 characters, must begin with an alpha character, cannot contain an embedded period, and cannot be the same as a procedure name in scope.


Variant data type

A special data type that can contain numeric, string, or date data as well as the special values Empty and Null.  The VarType function defines how the data in a Variant is treated.


watch expression

An expression you define to use in debugging an application.  A watch expression enables you to observe the behavior of a variable or expression throughout a procedure.  Watch expressions appear in the Watch pane of the Debug window when an application enters break mode.  Depending on the type of watch expression, you can choose to break program execution when the expression changes or evaluates to true.


Setup Kit Contents

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

Overview

How to Use the Setup Kit

Files You Are Allowed to Distribute

Files You Need to Distribute

Layout of the Distribution Disks

Modifying SETUP.LST

Compressing the Setup Files

Writing Your Setup Program

Where to Install Files on the User's Machine

Creating Your Distribution Disks

Testing Your Distribution Disks


See Also

Help:

Compressing the Setup Files

Creating Your Distribution Disks

Files You Are Allowed to Distribute

Files You Need to Distribute

How to Use the Setup Kit

Layout of the Distribution Disks

Modifying SETUP.LST

Overview

Testing Your Distribution Disks

Where to Install Files on the User's Machine

Writing Your Setup Program


Overview

See Also

You can freely distribute any application that you create with Visual Basic.  If you plan to distribute your application to a number of users or plan to sell it commercially, then you'll want to write a setup program that installs your application on the customer's machine.

The Visual Basic Setup Toolkit provides the tools you need to write setup programs using Visual Basic.  All the tools you need to use the Setup Toolkit are located in the \SETUPKIT subdirectory of the main Visual Basic directory.

The Setup Toolkit allows you to:

Create a customized setup program.

Compress and expand your application's files to fit the available disk space.

Preinstall files that you specify.

Use the version-stamping resources (VER.DLL) in Microsoft Windows to determine whether a file should be copied to the customer's machine.

Install files in the appropriate Microsoft Windows directories (\WINDOWS, \WINDOWS\SYSTEM) regardless of the actual directory names on your customer's system.

Create Microsoft Windows Program Manager groups and icons for your application.

The Setup Toolkit files include utilities, dynamic-link libraries (DLLs), and a sample setup program written in Visual Basic.  The following table describes each file:

File name	Description

SETUP.EXE	The preinstallation program (sometimes referred to as a bootstrap program) that your customer runs to install your application.  SETUP.EXE installs VER.DLL and all the files listed in SETUP.LST.  Your custom setup program (SETUP1.EXE or whatever file name you specify) is copied into the customer's \WINDOWS directory and then invoked to install your application.

SETUP1.EXE	A Visual Basic application that you customize.  This application's source files are located in the \SETUPKIT\SETUP1 subdirectory of the main Visual Basic directory.  Use these source files as a template for creating your own setup program.

SETUP.LST	A text file that lists all the files SETUP.EXE preinstalls on your customer's machine.  The first line of this file must be the name of your setup program (SETUP1.EXE or whatever file name you specify).

SETUP1.BAS	A collection of Visual Basic functions used in SETUP1.MAK to perform the tasks required by the setup program.

VER.DLL	A DLL that contains functions for copying and decompressing files.

VER.DLL can also detect the version of a file that has a Microsoft Windows version stamp.  You cannot compile version information in your Visual Basic .EXE file; however, some files do contain this version stamp.  If a file does not have a Microsoft Windows version stamp, VER.DLL uses the file date and time to determine the file version.

SETUPKIT.DLL	A DLL that contains various functions used in SETUP1.BAS.


How to Use the Setup Toolkit

See Also

You use the Setup Toolkit to create a setup program for your application using the following steps.  When you have finished this procedure, you'll have a set of distribution disks that a customer can use to install your application.

To create distribution disks for your application

1	Determine the files you need to distribute.

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

3	Compress the appropriate files.

4	Determine the layout of your distribution disks (which files on which disks).

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

6	Write your setup program.

7	Create your distribution disks.

8	Test your distribution disks.


Files You Need to Distribute

See Also

Before creating a setup program, you must determine which files to include on the distribution disks.  A setup program requires the following files:

File name	Description

SETUP.EXE	The preinstallation, or bootstrap, program.

SETUP1.EXE	Your customized setup program.

SETUP.LST	A text file that lists all the files SETUP.EXE preinstalls on your customer's machine.

VBRUN200.DLL	The Visual Basic run-time file required by all Visual Basic applications.

VER.DLL	A DLL that contains functions to locate the customer's \WINDOWS and \WINDOWS\SYSTEM directories and to use Microsoft Windows version-stamping information.

The user will need additional files to run your application [image] for example, data files, custom controls (.VBX), or DLLs.  Possible additional files include the following:

File name	Description

YOURAPP.EXE	Your application's .EXE file.

YOURAPP.DAT (optional)

YOURAPP.TXT (optional)

YOURAPP.INI (optional)	Data files (.DAT), text files (.TXT), or initialization files (.INI).

OLECLIEN.VBX (optional)	Required for the OLE client custom control.

OLECLI.DLL (optional)	Required for the OLE client custom control.

SHELL.DLL (optional)	Required for the OLE client custom control.

GRID.VBX (optional)	Required for the grid custom control.

DDEML.DLL (optional)	Required if your application uses DDE.

YOURCC.VBX (optional)	Custom controls that your application requires.

YOURDLL.DLL (optional)	Other DLLs that your application requires.

Note	Visual Basic does not compile custom controls and DLLs as part of your application's .EXE file.  If your application uses any custom controls or DLLs, you must include the appropriate .VBX and .DLL files on the distribution disks.


Modifying SETUP.LST

See Also

SETUP.LST is a text file that lists all the files SETUP.EXE preinstalls on your customer's machine.  After SETUP.EXE installs the files specified in SETUP.LST, it invokes your setup program.

The name of your setup program must be the first line in SETUP.LST.  You can give your setup program any name except SETUP.EXE, which is the name of the preinstallation program.  For example, you can name your setup program SETUP1.EXE, SETLOAN.EXE, or MYSETUP.EXE.

If you use SETUP1.MAK as a template for a setup program that doesn't call additional DLLs or use any custom controls, then SETUP.LST should contain only the name of your setup program, VBRUN200.DLL, and SETUPKIT.DLL.  Each file name in SETUP.LST must appear on a separate line.

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


Compressing the Setup Files

See Also

If all the files for your application will not fit on a single floppy disk, you can compress the files using the COMPRESS.EXE utility in the \SETUPKIT\KITFILES subdirectory.  Compressing your files might reduce the number of disks required to distribute your application.

COMPRESS.EXE is an MS-DOS-based utility, not a Microsoft Windows-based application.

To compress a file

At the MS-DOS prompt, type:

compress -r filename

The -r switch replaces the last character of the compressed file's file name with an underscore.  For example, to compress the file LOAN.EXE, type:

compress -r loan.exe

The result is a compressed file named LOAN.EX_

Note	You can compress any file on the distribution disks except SETUP.EXE, SETUP.LST, and VER.DLL.  You can compress as many files as you want.  VER.DLL correctly copies both compressed and noncompressed files to the user's disk if you use version 2.0 of COMPRESS.EXE, which comes with the Setup Toolkit.

Compressed files automatically return to their original name when expanded on the user's disk.

For information on COMPRESS.EXE, see the file COMPRESS.TXT in the \SETUPKIT\KITFILES subdirectory of the main Visual Basic directory.


Layout of the Distribution Disks

See Also

You must know the name of each file in your application and which distribution disk it is on before you write your setup program.

The first distribution disk must contain the following files:

SETUP.EXE

SETUP1.EXE (or whatever file name you specify)

SETUP.LST

VER.DLL

SETUPKIT.DLL

VBRUN200.DLL

Any other files listed in SETUP.LST (the files that will be preinstalled)

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

Note	The Setup Toolkit does not allow you to split a file between disks.


Where to Install Files on the User's Machine

See Also

Each Visual Basic application requires at least two files [image] the .EXE file and the run-time file VBRUN200.DLL.  Your application probably requires additional files.  Before writing your setup program, you must determine where on the user's disk you want to install each file.  The files that your application requires can be divided into several classes:

Program files

Initialization files

Operating-system components

Shared application resources

Program Files

These files are essential for your application and are useful only in the context of your application.  For example, your application's .EXE file and data files are considered program files.  Program files should be installed in the application directory.  The user is prompted for this directory during setup (sample code for this is included in SETUP1.MAK).

Initialization Files

These files control options for the user of an application.  Initialization (.INI) files should be installed in the user's Microsoft Windows directory, which is the directory in which the WIN.INI file is located (usually in the \WINDOWS subdirectory).  You determine the name of this directory on the user's disk by calling the GetWindowsDirectory Windows API function.  The code in SETUP1.MAK shows how to call this function.

Operating-System Components

These files are normally included with Microsoft Windows, but you may want to distribute them with your application to ensure that the user has a particular version of a DLL, such as OLECLIEN.DLL or SHELL.DLL.  You should install such files in the \SYSTEM subdirectory of the user's main Microsoft Windows directory.  You can determine the name of this directory by calling the GetSystemDirectory Windows API function.  The code in SETUP1.MAK shows how to call this function.

Shared Application Resources

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


Writing Your Setup Program

See Also

You can quickly write your setup program by modifying the source code of the sample setup program, SETUP1.MAK, located in the \SETUPKIT\SETUP1 subdirectory of the main Visual Basic directory.  SETUP1.MAK installs the sample application LOAN.EXE, which is located in the \SAMPLES\GRID subdirectory of the main Visual Basic directory.

LOAN.EXE uses the grid custom control and requires GRID.VBX to be properly installed on the user's system.  This is a typical setup scenario for applications that use custom controls.

To customize SETUP1.MAK so that it installs your application instead of LOAN.EXE, modify only the code in the Declarations section and the Form_Load event procedure of the SETUP1.FRM module.

To customize SETUP1.MAK

1	Modify the appropriate constants in the Declarations section of SETUP1.FRM.

2	In the Form_Load procedure of SETUP1.FRM, modify the arguments to the PromptForNextDisk function call.

3	Call the CopyFile function for each file on the current distribution disk.

4	Repeat steps 2 [image] 3 for each of the distribution disks, creating a new block of PromptForNextDisk and CopyFile calls for each disk.

5	Modify the arguments to the CreateProgManGroup and CreateProgManItem procedure calls.

SETUP1.FRM Constants

Several useful constants are defined in the Declarations section of SETUP1.FRM.  When customizing your setup program, redefine these constants to reflect information about your application.

Constant	Description

APPNAME	The name of your application.  Use this constant to display the name of your application in the captions of forms and in messages in the setup program.

APPDIR	The default directory in which your application is to be installed.

WINSYSNEEDED	The total size, in bytes, of all uncompressed files the setup program will install in the user's \WINDOW and \WINDOWS\SYSTEM subdirectories.  Use this number to determine whether the user has enough space on the disk that contains these subdirectories to install your application.

OTHERNEEDED	The total size, in bytes, of all uncompressed files the setup program will install in the application directory (the directory in which the user installs your application).  Use this number to determine whether the user has enough space to install your application on the disk that contains the application directory.

Example

This example of defining constants is taken from the Declarations section of SETUP1.FRM:

Const APPNAME = "Loan Application"

Const APPDIR = "C:\LOAN"

Const WINSYSNEEDED = 40896

Const OTHERNEEDED = 12555

PromptForNextDisk and CopyFile Functions

Use the PromptForNextDisk function to prompt the user to enter a disk.  If the user enters the correct disk, the function returns True.  Use the CopyFile function to copy a file from the distribution disk to the user's machine.  You must call CopyFile once for each file on the disk.  After copying all the files on a disk, call PromptForNextDisk again to prompt the user to insert the next disk.

Example

This example of the PromptForNextDisk and CopyFile functions is taken from the Form_Load event procedure of SETUP1.FRM:

' -----------

' Copy Files

' -----------

' Disk 1

' -----------

' Test to see if LOAN.EX_ is on the disk; if not, then you know the

' user did not insert the first disk.

If Not PromptForNextDisk(1, SourcePath$ + "LOAN.EX_") Then

GoTo ErrorSetup

End If

' Install LOAN.EXE in the destPath$.

If Not CopyFile(SourcePath$, destPath$, "LOAN.EX_", "LOAN.EXE", 0)

Then

GoTo ErrorSetup

End If

' Install GRID.VBX in the user's \SYSTEM directory.

If Not CopyFile(SourcePath$, winSysDir$, "GRID.VB_", "GRID.VBX", 0)

Then

GoTo ErrorSetup

End If

' -----------

' Disk 2

' -----------

' Test to see if FOO.DA_ is on the disk; if not, then you know the

' user did not insert the second disk.

If Not PromptForNextDisk(2, SourcePath$ + "FOO.DA_") Then

GoTo ErrorSetup

End If

' Install FOO.DAT in the destPath$.

If Not CopyFile(SourcePath$, destPath$, "FOO.DA_", "FOO.DAT", 0)

Then

GoTo ErrorSetup

End If

CreateProgManGroup and CreateProgManItem Functions

These functions create a Microsoft Windows program group and program item for your application.

Example

This example of the CreateProgManGroup and CreateProgManItem functions is taken from the Form_Load event procedure of SETUP1.FRM:

' --------------------------------------

' Create Program Manager group and icon.

' --------------------------------------

CreateProgManGroup Setup1, "Loan Application", "LOAN.GRP"

CreateProgManItem Setup1, destPath$ + "LOAN.EXE", "Loan Application"


Creating the Distribution Disks
Creating Your Distribution Disks

See Also

Before you copy files to the distribution disks, it's a good idea to label the disks.  On the first disk, attach a label that reads:

Disk1: Setup Disk

Insert this disk in drive A

In the Program Manager, choose Run from the File menu

Type a:setup and press Enter

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

Disk2: MyApp

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

To create distribution disks

1	Rename VER.DLL to VER.DL_.  For example:

rename a:ver.dll a:ver.dl_

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

2	Copy these files onto the first disk:

SETUP.EXE

SETUP.LST

SETUP1.EXE (or whatever you've named your setup program)

SETUPKIT.DLL

VER.DL_

VBRUN200.DLL

If you've compressed any of these files, the last character of the file name will be an underscore (for example, VBRUN200.DL_).

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


Testing Your Distribution Disks

See Also

You should test your distribution disks after you create them.  Be sure to test your setup program on a machine that does not have Visual Basic or any of the custom controls your application requires.

To test your setup program using the distribution disks

1	Insert the first disk in drive A.

2	From the Microsoft Windows Program Manager, choose Run from the File menu and type:

a:setup

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


Files You Are Allowed To Distribute

See Also

You can freely distribute any application that you create with Visual Basic.  In addition to an executable (.EXE) file, your application might require other files such as DLLs, custom controls (.VBX), or bitmaps (.BMP).

Standard Edition

You can legally distribute the following files with any Visual Basic application you create:

DDEML.DLL

GRID.VBX

OLECLI.DLL

OLECLIEN.VBX

SETUP.EXE (Setup Toolkit)

SHELL.DLL

VBRUN200.DLL

VER.DLL

WINHELP.EXE

Any files located in the \ICONS subdirectory of the main Visual Basic directory.

Professional Edition

If you have purchased the Professional Edition of Visual Basic, you can also distribute these files with any Visual Basic application you create:

ANIBUTON.VBX

CMDIALOG.VBX

COMMDLG.DLL

DBNMP3.DLL

GAUGE.VBX

GRAPH.VBX

GSW.EXE

GSWDLL.DLL

INSTCAT.SQL

KEYSTAT.VBX

MCI.VBX

MSCOMM.VBX

MSMAPI.VBX

MSMASKED.VBX

ODBC.DLL

ODBCINST.DLL

PENCTRL.VBX

PICCLIP.VBX

SETUP.EXE (ODBC setup)

SETUPI.DLL

SPIN.VBX

SQLSETUP.DLL

SQLSRVR.DLL

THREED.VBX

Any files located in the \BITMAPS subdirectory of the main Visual Basic directory.

Any files located in the \METAFILE subdirectory of the main Visual Basic directory.

Note	You may also be able to distribute other custom controls and DLLs that you have purchased.  See the licensing agreement supplied by the individual software vendor for details.


Icon Library

See Also

Visual Basic comes with a collection of over 450 icons in the ICONS directory that you can use to enhance your applications.  The Using Icons topic describes how to use icons in your applications.

The Icon Library includes these categories:

Arrows and pointers

Communication (networks, servers, printers, phones)

Computers (computers, disk drives, diskettes, keyboards, mouse devices)

 	Drag-and-drop (hands and arrows dragging and dropping file folders)

Elements (earth, water, fire, clouds, weather, the sun, phases of the moon)

Flags

Industry and transportation (bicycles, cars, airplanes, factories, tools)

Mail (mailboxes, envelopes, stamps, forms)

Miscellaneous (people, clocks, first-aid signs, locks and keys, buttons, punctuation marks, default form icons)

Office (card files, charts, file cabinets, folders, graphs, paper clips, labels)

Traffic signs

Writing (books, notepads, pens, pencils)

You can view the Icon Library either online with the IconWorks sample application included with Visual Basic, or in Appendix B, "Icon Library," of the Programmer's Guide.

Note	You may use the Icon Library icons or modified versions of them in your Visual Basic applications.  However, you are not allowed to make and sell copies of the Icon Library or any portion of it.


See Also

Help:

Assigning an Icon to a Form

Displaying Graphics on a Form

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Using Icons

See Also

There are a number of ways you can use icons to enhance your Visual Basic applications.  First determine the name and location of the file that contains the icon you want to use.  You can view the Icon Library icons to determine file names and directory locations using Appendix B, "Icon Library," of the Programmer's Guide, or by using the IconWorks sample application included with Visual Basic.

You can do the following with icons:

Display an icon on a form or in a picture box or image control during design time or run time.

Assign a drag icon to be displayed when a control is dragged during run time by setting the control's DragIcon property.

Assign an icon to a form to be displayed when the form is minimized during run time by setting the form's Icon property.

Assign an icon to a Visual Basic application  to be displayed in a Microsoft Windows program group by specifying the form whose icon is to be used in the Make EXE File dialog box.

Tips

For a minimized form, an application in a Microsoft Windows program group, and a control being dragged, the graphic representation must be in icon (.ICO) format.

You can view, modify, and create icons with the IconWorks sample application included in the \SAMPLES\ICONWRKS subdirectory of the main Visual Basic directory.

Some pairs of the Icon Library icons can be used in tandem.  For example, the pair of icons below represent the same file cabinet with its bottom drawer open and closed.

The unfilled parts of Icon Library icons are transparent.  This makes the background color of your control, form, or desktop visible.


See Also

Help:

Assigning an Icon to a Form

Displaying Graphics on a Form

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Keyboard Guide


Keyboard Guide

Code Window Keys

Debug Window Keys

Form Window Keys

Global Keys

Menu Design Window Keys

Project Window Keys

Properties Window Keys

Toolbox Keys


Global Keys

Use these key combinations in all Visual Basic windows:

Press	To

F5	Run an application.

F8	Execute code one line at a time.

Shift+F8	Execute statements one line at a time without stepping into procedure  calls.

Ctrl+Break	Stop running a Visual Basic application.

Ctrl+B	Show the Debug window (break mode only).

Shift+F5	Restart an application from the beginning after an interruption.

Use these key combinations in all Windows-based applications:

Press	To

F1	Open Help.

Alt+F6	Toggle between the last two active windows.

Alt+Esc	Cycle through top-level Windows-based applications.

Alt+Tab	Cycle through top-level Windows-based applications, restoring minimized applications.

Ctrl+Esc	Open the Task List.

Alt+Hyphen	Open the current window's Control menu.

Alt+Spacebar	Open the application's Control menu.

Alt or F10	Select the Control-menu box.

Alt+F4	(Visual Basic) Close the active window; if all windows are closed, close Visual Basic.

Alt+F4 	Close the application.

Ctrl+C	Copy the selection to the Clipboard.

Ctrl+X	Cut the selection to the Clipboard.

Ctrl+V	Paste the Clipboard selection.

Ctrl+Z	Undo the last edit.


Code Window Keys

Use these key combinations in the Code window:

Press	To

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

Ctrl+C	Copy the selected text to the Clipboard.

Ctrl+X	Cut the selected text to the Clipboard.

Del	Delete the selected text without placing it on the Clipboard.

Ctrl+V	Paste the Clipboard contents at the insertion point.

Ctrl+Z	Undo the last editing action in the current line.

Ctrl+N	Insert a blank line above the current line.

Ctrl+Y	Cut the current line to the Clipboard.

F2	Display the View Procedures dialog box.

Ctrl+F2	Move the insertion point into the Object box.

Shift+F2	Go to the definition of the selected procedure.

Ctrl+Down Arrow	Display the next procedure.

Ctrl+Up Arrow	Display the previous procedure.

Page Down	Page down through the procedures in your code.

Page Up	Page up through the procedures in your code.

Ctrl+Page Down	Shift viewing of your code one page to the right.

Ctrl+Page Up	Shift viewing of your code one page to the left.

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

F9	Set or remove a breakpoint.

F3	Find Next: repeat text search down through your code.  If no text search has been done, the Find dialog box is displayed.

Shift+F3	Find Previous: repeat text search up through your code.  If no text search has been done, the Find dialog box is displayed.

F5	Run an application (or continue running, if in break mode).

F8	Execute code one line at a time (single step).

Shift+F8	Execute code one procedure at a time (procedure step).

Ctrl+Break	Stop running a Visual Basic application.

Shift+F5	Restart an application from the beginning.

Use these key combinations for menu shortcuts in the Code window:

Press	To

Ctrl+D	Add File

Ctrl+S	Save File

Ctrl+A	Save File As

Ctrl+P	Print

Ctrl+F	Find

F3	Find Next

Shift+F3	Find Previous

Ctrl+R	Replace

Shift+F9	Instant Watch (break mode only)

Ctrl+W	Edit Watch

Ctrl+L	Calls Window (break mode only)

Ctrl+B	Debug window (break mode only)


Form Window Keys

Use these key combinations in the Form window:

Press	To

Shift+Ctrl+Alpha	Select a property in the Property list of the Properties window.

Alpha	Enter a value in the Settings box in the Properties window.

F7	Open the Code window for the selected object.

Ctrl+C	Copy the selected controls to the Clipboard.

Ctrl+X	Cut the selected controls to the Clipboard.

Del	Delete the selected controls without placing them on the Clipboard.

Ctrl+V	Paste the Clipboard contents on the form.

Ctrl+Z	Undo a deletion of controls.

Tab	Cycle forward through controls in tab order.

Shift+Tab	Cycle backward through controls in tab order.

Ctrl+Click	Add or remove a control from the selection.

Click+Drag	Select multiple controls.

Ctrl+Click+Drag	Add or remove controls from the current selection.

Ctrl+M	Display the Menu Design window (design time only).

F4	Display the Properties window (design time only).

Ctrl+ =	Bring to front (affects overlapping controls at design time only).

Ctrl+Hyphen	Send to back (affects overlapping controls at design time only).

To deselect all controls, click the form.  To select controls in a container, first deselect the container and then Ctrl+Click+Drag around the desired controls.


Debug Window Keys

Use these key combinations in the Immediate pane of the Debug window:

Press	To

Enter	Run a line of code.

Ctrl+Z	Undo the last edit action in the current line.

Ctrl+C	Copy the selected text to the Clipboard.

Ctrl+V	Paste the Clipboard contents at the insertion point.

Ctrl+X	Cut the selected text to the Clipboard.

Ctrl+L	Display Calls dialog box (break mode only).

Ctrl+W	Display Edit Watch dialog box.

Shift+F9	Display Instant Watch dialog box.

F5	Continue running an application.

Shift+F5	Restart an application.

F8	Execute code one line at a time (single step).

Shift+F8	Execute code one procedure at a time (procedure step).

Del	Delete the selected text without placing it on the Clipboard.

F2	Display View Procedures dialog box.

Ctrl+Enter	Insert carriage return.

F6	Switch to Watch pane.

Use these key combinations in the Watch pane of the Debug window:

Press	To

Enter	Display Edit Watch dialog box for selected watch expression.

F2	Display View Procedures dialog box.

F6	Switch to Immediate pane.

Ctrl+F	Find.

F3	Find Next.

Shift+F3	Find Previous.

Ctrl+R	Replace.

Ctrl+ =	Bring to front.

Ctrl+Hyphen	Send to back.

Ctrl+Down	Next Procedure.

Ctrl+Up	Previous Procedure.

Shift+F2	Procedure Definition.

Right Arrow	Shift viewing of the watch expression to the right.

Left Arrow	Shift viewing of the watch expression to the left.


Menu Design Window Keys

Use these key combinations in the Menu Design window:

Press	To

Tab	Cycle forward through the boxes and buttons.

Shift+Tab	Cycle backward through the boxes and buttons.

Enter	Cycle forward through menu items.

Alt+R	Move an item to a lower level in a hierarchical menu.

Alt+L	Move an item to a higher level in a hierarchical menu.

Alt+U	Move an item one line up.

Alt+B	Move an item one line down.

Use these key combinations when the Shortcut list box has the focus in the Menu Design window:

Press	To

F4	Open or close the list.

Alt+Down Arrow	Open or close the list.

Alt+Up Arrow	Open or close the list.

Page Down	Move to the last item in the list.

Page Up	Move to the first item in the list.

End	Move to the last item in the list.

Home	Move to the first item in the list.


Properties Window Keys

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

Press	To

F2	Switch focus to the Settings box.

F4	Switch focus to and open the Settings box.

Shift+Tab	Switch focus to the Object box.

Page Down	Move down through the Property list.

Page Up	Move up through the Property list.

Down Arrow	Move down through each property.

Up Arrow	Move up through each property.

Right Arrow	Move down through each property.

Left Arrow	Move up through each property.

End	Move to the last property in the list.

Home	Move to the first property in the list.

Alt+F6	Switch from the Properties window to the form.

Alpha	Enter setting for the selected property

Tab	Move the insertion point to the Settings box.

Ctrl+Shift+Alpha	Move to the next property in the list that begins with the alpha character.

Double-Click	Cycle through settings of enumerated properties or to switch focus to the Settings box for other property types.

Use these key combinations when the Settings box has the focus in the Properties window:

Press	To

Ctrl+Z	Undo the last editing action in the current line.

Ctrl+C	Copy the selected text to the Clipboard.

Ctrl+X	Cut the selected text to the Clipboard.

Del	Delete the selected text without placing it on the Clipboard.

Ctrl+V	Paste the Clipboard contents at the insertion point.

Enter	Move the insertion point into the Property list and commit the property change.

Shift+Tab	Switch focus to the Object box.

Tab	Move the focus to the Property list.

Esc	Cancel the property change.

Use these key combinations when a property has enumerated values and the Settings box has the focus in the Properties window:

Press	To

F4	Open or close the Settings box list.

Alt+Down Arrow	Open or close the Settings box list.

Alt+Up Arrow	Open or close the Settings box list.

Page Down	Move to the last item in the Settings box list.

Page Up	Move to the first item in the Settings box list.

Down Arrow	Move down through the items in the Settings box list.

Up Arrow	Move up through the items in the Settings box list.

Right Arrow	Move down through the items in the Settings box list.

Left Arrow	Move up through the items in the Settings box list.

End	Move to the last item in the Settings box list.

Home	Move to the first item in the Settings box list.

Use these key combinations when you set the BackColor, ForeColor, FillColor, or BorderColor properties, and the Settings box has the focus in the Properties window:

Press	To

Alt+Down Arrow	Display the Color palette.

Alt+Up Arrow	Display the Color palette.

Del	Reset to (None).

Use these key combinations when you set the Icon or Picture properties, and the Settings box has the focus in the Properties window:

Press	To

Alt+Down Arrow	Display the Load Icon or Load Picture dialog box.

Alt+Up Arrow	Display the Load Icon or Load Picture dialog box.

Del	Reset to (None).


Project Window Keys

Use these key combinations in the Project window:

Press	To

Enter	Open the selected file from the list.

Shift+Enter	Open the Code window for the selected file.

F7	Open the Code window for the selected file.

Home	Select the first file in the list.

End	Select the last file in the list.

Tab	Cycle between the list, the View Form, and the View Code buttons.


Toolbox Keys

Use these key combinations in the Toolbox:

Press	To

Enter	Place the selected control on the active form.

Down Arrow	Select the next tool down.

Up Arrow	Select the next tool up.

Left Arrow	Select the tool to the left.

Right Arrow	Select the tool to the right.

Tab	Move down through the Toolbox.

Shift+Tab	Move up through the Toolbox.

End	Select the last tool in the Toolbox.

Home	Select the pointer tool.


access key

A key pressed while holding down the Alt key that enables the user to open a menu, carry out a command, select a control, or move to a control.


active window

The window that appears in the foreground with a highlighted title bar or border to distinguish it from other visible windows.


ANSI Character Set

American National Standards Institute (ANSI) 8-bit character set used by Microsoft Windows that enables you to represent up to 256 characters (0-255) using your keyboard.  The first 128 characters (0-127) correspond to the letters and symbols on a standard U.S. keyboard.  The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


application

A collection of code and visual elements that work together as a single program.  Developers build and run applications within the Visual Basic environment, while end users run applications outside of Visual Basic.


argument

A constant, variable, or expression passed to a procedure.


ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent the letters and symbols found on a standard U.S. keyboard.  The ASCII character set is the same as the first 128 characters in the ANSI character set.


assignment statement

A statement such as Text1.Text = "My Name" that assigns a value to a variable or to a property.


automatic formatting

A Code window feature that automatically formats code as you enter it by capitalizing the first letter for keywords, regularizing spacing, adding punctuation, updating references to variables and procedure names, and setting the foreground colors as specified by the Environment settings from the Options menu.


binary format

Encoded in a machine-readable format.  Different from ASCII or ANSI formats, which encode data as text.


bit

The smallest unit of data a computer can store.  Bits are expressed as 1 or 0.


bit field

A value in which each bit represents a state or condition.  1 indicates the state or condition is on and 0 indicates it is off.


bit mask

A value used with bit-wise operators (And, Eqv, Imp, Not, Or, Xor) to test, set, or reset the state of individual bits in a bit-field value.


bitmap

A graphic object stored as a collection of bits; a map of the display pixels that make up a picture.  Each pixel is represented by single or many bits.


bitwise
bit-wise

A bit-by-bit operation of indentically positioned bits in two numeric expressions.


block If

Any If...Then statement of more than one line is considered a "block If."  It requires End If as the last line of the statement block.


Boolean expression

An expression that evaluates to either one of two states [image] for example, On or Off.  The Off state is always zero and is represented by the intrinsic constant False.  The non-False state has two definitions: one bit-wise, the other logical.  The bit-wise definition is represented by the intrinsic constant True and always equals -1.  The logical definition is used in testing for conditional expressions in statements such as If condition Then..., or While condition...Wend, where any expression that evaluates to nonzero (including -1) fulfills the condition.


break mode

In the development environment, break mode is the temporary suspension of program execution.  In break mode, you can examine your program, make certain kinds of edits, use debugging tools or choose to continue execution, restart execution from the beginning of your application, restart from a chosen point, or end execution and return to design mode.


breakpoint

In the development environment, an attribute at which execution automatically stops, putting the application in break mode.


Cancel button

A button you click to cancel changes.  This is also the generic term for any command button on a form that has the Cancel property set to True, allowing you to press Esc or to click the button to cancel changes on that form.


Caption

The property you set to specify the text displayed on a control or form.


cascading event

A sequence of events caused by an event procedure directly or indirectly calling itself.  Often results in an "Out of stack space" error.  It is also called an event cascade or recursion.


check box

A control used to represent an option (on/off, true/false) you can set by selecting or clearing.  An X in a check box indicates it is selected.


client

In an active link of a dynamic data exchange (DDE) conversation, refers to an application, form, or control that requests data from another application acting as a server.  Note the terms "client" and "server" have been replaced in DDE terminology with the terms "destination" and "source."


Clipboard

A temporary storage location used to transfer text, graphics, or code between forms and modules or between Windows-based applications.


combo box

A control, similar to a text box and a list box combined, in which the user can either enter a value or select from a list of options.


command line

The path, file name, and argument information provided by the user to run a program.


comment

Text that explains code.  Comments begin with an apostrophe (') or with the word "REM".


container

A parent object that contains child forms or controls.


control

An object that has a set of properties and one or more events it recognizes that you can place on a form.  You use controls to get user input, display output, and to trigger event procedures.  You can manipulate most controls using methods.  Some controls are interactive (responsive to user actions), while others are static (accessible only through code).


Control-menu box

Opens the Control menu, which displays commands that enable you to move or resize the title bar, to switch to other Windows-based applications, or to close the current application.


Control-menu commands

Commands that enable you to move or resize the title bar, to switch to other Windows-based applications, or to close the current application.


constant

A value that cannot change during program execution, including literal numbers, strings, and symbolic constants defined with the Const statement.


control array

A group of controls of the same type that share a common name, type, and event procedures.  Each constituent control has a unique index number.  When a control in the array recognizes an event, it calls the event procedure for the group and passes the index as an additional argument, allowing your code to determine which control recognized the event.


Control Panel

A program built into Microsoft Windows that controls your system configuration.  Through the Control Panel, you can adjust various hardware and software options such as desktop colors and patterns, printers, date and number formats, and fonts for printers and monitors.


cross hair

A cross-shaped pointer displayed when you select a control from the Toolbox and move the mouse over a form.  In the MousePointer property, this pointer is called "Cross."


custom control

A DLL file having the extension .VBX which, when loaded into Visual Basic, extends the Toolbox by adding extra controls.


DDE

Dynamic data exchange [image] an established protocol for exchanging data through active links between applications that run under Microsoft Windows.


declaration

Definition of a constant, variable, or user-defined type, that specifies the name and data type; for DLL procedures, specifies the name, library, and arguments.


design time

Any time when you're building an application in the design environment [image] creating controls, setting control or form properties, writing code, and so on.  In contrast, during run time, you run and interact with the application as if you were a user.


device context

A link between a Windows-based application, a device driver, and an output device such as a display, printer, or plotter.


dialog box

A type of form you can create in a Form window.  A dialog box can either request information the application needs or provide extra information to the user.  Normally, dialog boxes are shown modally.


DLL

Dynamic-link library [image] a library of routines loaded and linked into applications at run time.  DLLs include utility routines for standard application tasks such as retrieving configuration information, managing memory, and handling user actions.  Custom controls are DLLs used to add controls.  Other DLLs may provide specific functions not intrinsic to Microsoft Windows.


drag-and-drop operation

Features that enable the user to drag a control and drop it onto a form or another control using the mouse.  An object can be a source (an item the user drags) or a target (an item on which the user drops a source).


editing key

The Insert, Delete, or Backspace key.


Enter button

A button next to the Settings box in the Properties window that you click to save changes in a property setting.


enumerated data type

A data type simulated with the Integer data type that applies to certain form and control properties.


event

An action recognized by a form or control, such as clicking the mouse or pressing a key.  Events can occur as the result of user action or program code, or they can be triggered by the system.


event procedure

A procedure invoked in response to an event.  An event can be caused by the user or program code, or it can be triggered by the system.


executable file

A Windows-based application that can run outside the development environment.


expression

A combination of functions, operators, variables, and constants that yields a single value.  An expression can perform a calculation, manipulate characters, or test data.


focus

In the Microsoft Windows environment, only one window, form, or control can receive mouse clicks or keyboard input.  This object "has the focus."  The focus can be set by the user or by the application.  Focus is usually indicated by a highlighted caption or border.


form

A window or dialog box.  Forms are containers for controls.  An MDI form can also be a container for child forms and some controls.


form code

All the procedures and declarations saved in the same file as a form and its controls.  Procedures in a form file are callable only from within that file.


frame

A rectangular control.  Provides a graphical and functional grouping for controls.


function key

Any of the keys labeled F1 through F16.  Function keys often handle shortcuts for frequently carried out commands and actions.  You can assign a function key as a shortcut key.


Function procedure

A procedure that performs a specific task within a program and returns a value.  A Function procedure begins with a Function statement and ends with an End Function statement.


general procedure

A procedure that must be explicitly called by another procedure, unlike an event procedure, which remains idle until invoked in response to events caused by the user or program code or that were triggered by the system.


graphics method

A method that operates on a form, picture box, or the Printer object and performs run-time drawing operations, including animation or simulation.  The graphics methods are Circle, Cls, Line, Point, Print, and PSet.


grid

The dots or points, measured in pixels, on the Form window when you're in design mode.  Using this grid ensures that controls are positioned uniformly.


handle

A unique integer value used to identify and access a window, form, or control.


hierarchical menu

A menu that contains at least one level of submenus.


horizontal scroll bar

A control consisting of a horizontal bar, two scroll arrows, and a small box to enable various scrolling methods.  Primarily used as a graphical tool for quickly navigating through a long list of items or a large amount of information, and for indicating the current position on a scale.  Can also be used as an input device or an indicator of speed or quantity.


icon

A graphic representation of an object or concept; commonly used to represent minimized applications in Microsoft Windows .  Essentially a bitmap (an image made up of pixels on the screen) with a maximum size of 32 x 32.


index

A number that identifies an element in an array, control array, or a collection.


insertion point

The place where text is inserted when you type; usually indicated by a text cursor.


keyboard modifier

Refers to the Shift, Ctrl, or Alt key.  One or more of these keys are often combined with another keyboard command to modify the action carried out by that command.


keyword

A symbol recognized as part of the programming language [image] for example, a statement or function name, operator, or method.


label

A control that contains text the user cannot directly change during run time.


line label

A line label, used to identify a single line of code in a form or module, may be any unique combination of no more than 40 characters, starting with a letter and ending with a colon.


line number

A line number, used to identify a single line of code in a form or module, can be any unique combination of no more than 40 digits.


list box

A control that displays a list of choices.


logic error

A programming error that could cause code to produce the wrong results or halt execution.  May be caused by mixups in variable names or wrong variable types, endless loops, flaws in logical comparisons, or array problems.


Long data type

A four-byte integer (whole number between -2,147,483,648 and 2,147483,647, inclusive).


Maximize button

A button in the upper-right corner that enlarges a window to fill the entire screen.


metafile

A file that stores an image in terms of graphical objects (lines, circles, polygons) rather than pixels.  When resized, a metafile tends to preserve an image better than a bitmap does.


method

A keyword that operates on an object or form.  Similar to a function or a statement, with the difference that methods often operate differently on different objects.  Methods pertain mainly to techniques for displaying forms and controls, and drawing graphics and text.


millisecond

One one-thousandth of a second.


Minimize button

A button in the upper-right corner that shrinks a window to an icon.


modal

A type of window or dialog box that requires the user to take some action before the focus can switch to another form or dialog box.


modeless

Describes a window or dialog box that does not require user action before the focus can switch to another form or dialog box.  The Code window is an example of a modeless window.


module

The procedures and declarations not associated with a form, but stored together in a single file and recognized throughout an application.  Often called a code module.


module level

The declarations section of a form or module.


navigation key

A key used for moving and selecting, such as the Home, End, PageUp, PageDown, Up Arrow, Down Arrow, Right Arrow, Left Arrow, and Tab keys.


object

In Visual Basic, a term that refers to forms, controls, and the App, Clipboard, Debug, Printer, and Screen objects.


Object box

  A list box located at the upper-left corner of the Code window that lists forms and controls in the form to which the code is attached.  Also, a list box located at the top of the Properties window that lists the form and its controls.


OLE

Object linking and embedding [image] the process of creating applications that contain components from various other source applications.


option button

A control used to display an option or, more typically, a group of related options from which you can select only one.


Paste Link command

A command that inserts Clipboard contents copied from another Windows-based application.  It also creates a link with that application to update the copied data automatically.


path

A designation for the location of files or directories on your disk.  For example, C:\VB\ICONS is the path to the \ICONS subdirectory of the \VB directory on drive C.


pen

The color specified by a Line, Point, or Circle statement, or by the current ForeColor or FillColor setting.


persistent bitmap

A bitmap, accessed with the Image property, that stores output from graphics methods (Circle, Line, Point, Print, and PSet) in memory.  This output, or "persistent graphics," is redrawn when certain kinds of screen events occur [image] for example, when a form is redisplayed after being hidden behind another window.


picture box

A control that can contain a graphical image (bitmap, icon, or metafile), other controls, or can serve as a drawing area for graphics methods.  Can also be a container for other controls, can be used to group controls such as to create an option button grouping, or create a toolbar on a form.


pixel

An abbreviation for picture element; a dot that represents the smallest graphic unit of measurement on a screen.  A pixel is a screen-dependent unit:  the dimensions of screen elements vary with the display system and resolution used.  By contrast, the twip is a screen-independent unit of measure.


poke

To modify data in a source application without the source application's explicit permission, as in the LinkPoke DDE method.


point

In typesetting, a point is 1/72 inch.  The height of fonts is usually expressed in points.


Printer object

A drawing object you use in code to determine how text and graphics are printed on a page and to send output directly to a printer.


Proc box

A list box located at the upper-right of the Code window which displays the event procedures Visual Basic recognizes for the form or control displayed in the Object box.


procedure

A sequence of code statements executed as a unit; refers to both Sub and Function procedures.


procedure call

Tells Visual Basic to execute a procedure.


procedure level

The location of statements within a Sub or Function procedure.


procedure template

The beginning and end statements that are automatically provided when you specify a Sub procedure, Function procedure, or event procedure in the Code window.


project

A collection of forms, modules, and custom controls that make up an application.


Project window

A window that displays a list of all the forms and modules in your project or application.


Property list

A two-column list in the Properties window that shows all properties and their current settings for the selected object.


Properties window

A window used to display or change the design-time properties of a selected form or control.


property

A named attribute of a form or control.  You set properties to define an object's characteristics (such as size, color and screen location) or behavior (whether it is enabled or not).  Some properties are accessible only at run time or only at design time.


relational operators

Symbol	Description

<	Less than

<=	Less than or equal to

>	Greater than

>=	Greater than or equal to

<>	Not equal

=	Equal


reserved word

A keyword that can only be used in conformity with its syntax; it includes predefined statements, methods, functions, and operators.


Restore button

A button in the upper-right corner of a maximized window that returns the window to its original size.


run time

Any time when an application is running.  During run time, you can interact with an application as a user would.  In contrast, during design time you build the application using the design environment.


run-time error

An error that occurs when an application is running.


scoping

The parts of a program in which a symbol or object exists or is visible.  Depending on where it is declared, a variable or constant may have lifetime or visibility only in a specific form, module, or procedure.


separator bar

A bar that divides commands into logical groups on a menu.


Settings box

A text box in the top of the Properties window in which you select, modify, or enter property settings.


server

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


shortcut key

A function key or key combination (such as F5 or Ctrl+C) that carries out a command.


split bar

The thin bar below the title bar of the Code window used to divide the window into two panes, each separately scrollable vertically and horizontally.


statement

A combination of keywords, variables, and operators recognized as a unit of code.


String data type

Data comprising a sequence of contiguous characters, including letters, numerals, spaces, and punctuation marks.


submenu

A menu that is opened from another menu.  It displays its own list of commands.


Sub procedure

A procedure that performs a specific task within a program but returns no value.  A Sub procedure begins with a Sub statement and ends with an End Sub statement.


syntax

The way that programming language elements must be used in executable statements.


syntax checking

A Code window feature that automatically checks the syntax of each line of code you enter.


syntax error

An error that occurs when syntax rules have been violated.


tab order

The order (as set by the TabIndex property) in which the focus moves between controls on a form as the user presses the Tab or Shift+Tab key.


text box

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


text file

A file that is meant to contain only ASCII text.


title bar

An area at the top of a window that displays the window's caption or name.


twip

A unit of screen measurement.  There are approximately 1440 twips to a logical inch or 567 twips to a logical centimeter [image] the length of a screen item measuring one inch or one centimeter when printed.  A twip is a screen-independent unit used to ensure that placement and proportion of screen elements in your application are the same on all display systems.  Contrast with pixel, a screen-dependent unit of measurement.


variable

A memory location for data that can change as the application runs.  Each variable has a unique name that identifies it within its level of scope.


Windows API

API is an acronym for Application Programming Interface.  Consists of the functions, messages, data structures, data types, and statements you can use in creating applications that run under Microsoft Windows.  The parts of the API you use most are code elements included for calling API functions from Windows.  This includes procedure declarations (for the Windows functions), user-defined type definitions (for data structures passed to those functions), and constant declarations (for values passed to and returned from those functions).


three-dot button

A button in the Properties window that opens a dialog box in which you select or enter settings for certain properties.


Shortcut box

A drop-down list box in the Menu Design window from which you select a shortcut key for a menu item.


default color box

A box in the Color palette that displays the currently selected foreground and background colors for the form or control.


Checked check box

A check box in the Menu Design window that you select to have a check mark appear at the left of a menu item whenever the user selects that item.


Enabled check box

A check box in the Menu Design window that you select if you want the menu item to respond to events or to be unavailable and appear dimmed.


Visible check box

A check box in the Menu Design window that you select if you want the menu item to appear on the menu.


Can't open Clipboard

You have 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 opened and close it.


Can't paste

Make sure the ServerType and Protocol properties are set appropriately.  The PasteOK property returns True when an object can be pasted from the Clipboard.


Cannot execute object

You have attempted to send an execute string to a server application (Action = 8), but the server application does not support the StdExecute protocol.


Class is not set

For Action = 0 (CreateNew) and Action = 1 (CreateFromFile), the Class property must be set.


Invalid format on set data or set data text

You have attempted to set data with the Data or DataText property using an invalid data format.


Invalid property value

You have attempted to assign an invalid value to a property.  This error also occurs when you attempt to perform an action that requires several properties to be set and one of the properties is set to an invalid value.


No object

You have tried to perform an action on an object, but an object has not yet been created.


Object closed

You cannot close an object that does not exist or is not active.  If the object exists, set Action = 7 to activate it.


Object not empty

You attempted to create an object, but one already exists.  Delete the existing object (Action = 10) before creating a new object.


OLE_BUSY

Tried to execute a method or action while another method or action was in progress.


OLE_ERROR_ABORT

Client chose to abort during drawing.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_ADDRESS

One of the pointers is invalid.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_ADVISE_NATIVE

An item could be missing.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_ADVISE_PICT

An item could be missing or the server application doesn't support this format.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_ADVISE_RENAME

The server application doesn't support Rename.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_BLANK

Critical data missing or invalid.  Possible causes:

The ServerType property may be incompatible with the Action property when creating an object.

The SourceDoc property is not set.


OLE_ERROR_CANT_UPDATE_CLIENT

The client does not accept updates from the server application.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_CLASS

The specified class is invalid.  Use the ServerClasses and ServerClassCount properties to get a list of available classes on your system.  Note that some class names are case-sensitive.


OLE_ERROR_CLIPBOARD

Failed to get or set data from the Clipboard.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_COMM

The client failed to communicate with the server application.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_COMMAND

The string specified in the Execute property generated an error in the server application.


OLE_ERROR_DATATYPE

The data format returned by the Data or DataText property is not the same data format specified by the Format property.


OLE_ERROR_DOVERB

The value specified in the Verb property caused an error in the server application.


OLE_ERROR_DRAW

Unable to draw.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_DRIVE

The drive letter for the document is invalid.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_FORMAT

The requested format is not available.  Use the ServerAcceptFormats and ServerAcceptFormatsCount properties to get a list of acceptable formats.


OLE_ERROR_GENERIC

An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_HANDLE

Invalid handle.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_LAUNCH

When creating a new object or updating an existing object, the executable file associated with the Class property (for example, EXCEL.EXE) must be either active or on the system's directory path.


OLE_ERROR_MEMORY

Could not allocate or access memory.


OLE_ERROR_METAFILE

Invalid metafile.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NAME

Invalid document or object name.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NETWORK

Failed to establish connection to a network on which the document is located.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NEW

The server application failed to create the new document.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NOT_EMPTY

Client document contains objects.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NOT_EQUAL

Objects are not equal.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NOT_LINK

Not a linked object.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_NOT_OPEN

The object is not open for editing.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_OBJECT

Not a valid object for the action.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_OPEN

The server application failed to open the document.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_OPTION

Invalid option while updating or drawing.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_OUTOFDATE

The object is out of date.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_PALETTE

Invalid Color palette.


OLE_ERROR_POKE_NATIVE

Couldn't poke native data to the server application.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_PROTECT_ONLY

OLE APIs have been called while the processor was in real mode.


OLE_ERROR_PROTOCOL

Possible causes:

The Protocol property is missing or invalid.

The object data file was invalid while attempting to read the file (Action = 12).  Make sure the object data file was saved correctly (Action = 11).


OLE_ERROR_REGISTRATION

The server application isn't registered in the system's registration database.  If the server application was not installed correctly, the system's registration database may not be updated correctly.


OLE_ERROR_REQUEST_NATIVE

The server application failed to render native data.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_REQUEST_PICT

The server application failed to render presentation data.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_SERVER_BLOCKED

The application attempted to block or revoke a blocked server application or document.


OLE_ERROR_SHOW

An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_SIZE

Incorrect buffer size.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_STATIC

A static object was used for an action or method that requires a non-static object.


OLE_ERROR_STREAM

Unable to read or write the object data file.  Possible causes:

The FileNumber property was invalid while attempting to load or save the object data file.

The object data file wasn't opened in Binary mode.

Unable to write file due to lack of disk space.


OLE_ERROR_SYNTAX

The string for the Execute property generated a syntax error by the server application.


OLE_ERROR_TASK

The server or client task is invalid.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_TEMPLATE

The server application failed to load the template.  An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_TERMINATE

An unexpected error occurred in OLECLI.DLL.


OLE_ERROR_UPDATE

The client wasn't able to update the object.


OLE_OK

The function operated correctly.


OLE_WAIT

A command has been initiated; the client must wait for OLE_RELEASE in the callback function.  An unexpected error occurred in OLECLI.DLL.


Out of memory

Unable to allocate memory for the control.


Property is read-only

You attempted to assign a value to a read-only property.


Property is write only
Property is write-only

You have tried to read a value from a write-only property, such as the Action property.


Server class was not specified before the registration database was accessed

Occurs if the ServerClass property is not properly set when an attempt is made to access ServerAcceptFormats, ServerAcceptFormatsCount, ServerGetFormats, ServerGetFormatsCount, ServerProtocol, ServerProtocolCount, ServerVerbs, or ServerVerbsCount.


Source document is not set

The SourceDoc property wasn't set when attempting to create an object.


Source item is not set

The SourceItem property wasn't set when attempting to create an object.


This action is reserved for future use

You have attempted to use an action that is reserved for future use (Action = 3).


Type of object cannot be created

The ServerType isn't compatible with the type of object you are trying to create.  When creating:
This type of object:	Set ServerType to:
New object (Action = 0)	1 (Embedded)
From File (Action = 1)	0 (Linked)


ANSI Character Set

Characters 128 - 255

 0	 32	[space] 	 64	@	 96	`

 1	 33	!	 65	A	 97	a

 2	 34	"	 66	B	 98	b

 3	 35	#	 67	C	 99	c

 4	 36	$	 68	D	 100	d

 5	 37	%	 69	E	 101	e

 6	 38	&	 70	F	 102	f

 7	 39	'	 71	G	 103	g

 8	* *	 40	(	 72	H	 104	h

 9	* *	 41	)	 73	I	 105	i

 10	* *	 42	*	 74	J	 106	j

 11	 43	+	 75	K	 107	k

 12	 44	,	 76	L	 108	l

 13	* *	 45	-	 77	M	 109	m

 14	 46	.	 78	N	 110	n

 15	 47	/	 79	O	 111	o

 16	 48	0	 80	P	 112	p

 17	 49	1	 81	Q	 113	q

 18	 50	2	 82	R	 114	r

 19	 51	3	 83	S	 115	s

 20	 52	4	 84	T	 116	t

 21	 53	5	 85	U	 117	u

 22	 54	6	 86	V	 118	v

 23	 55	7	 87	W	 119	w

 24	 56	8	 88	X	 120	x

 25	 57	9	 89	Y	 121	y

 26	 58	:	 90	Z	 122	z

 27	 59	;	 91	[	 123	{

 28	 60	<	 92	\	 124	|

 29	 61	=	 93	]	 125	}

 30	 62	>	 94	^	 126	~

 31	 63	?	 95	_	 127

* *	Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return characters, respectively.  They have no graphical representation but, depending on the application, may affect the visual display of text.

These characters aren't supported by Microsoft Windows.


ANSI Character Set
ANSI Character Set (128 - 255)

Characters 0 - 127

 128	 160	[space]	 192	À	 224	à

 129	 161	¡	 193	Á	 225	á

 130	 162	¢	 194	Â	 226	â

 131	 163	£	 195	Ã	 227	ã

 132	 164	¤	 196	Ä	 228	ä

 133	 165	¥	 197	Å	 229	å

 134	 166	¦	 198	Æ	 230	æ

 135	 167	§	 199	Ç	 231	ç

 136	 168	¨	 200	È	 232	è

 137	 169	©	 201	É	 233	é

 138	 170	ª	 202	Ê	 234	ê

 139	 171	«	 203	Ë	 235	ë

 140	 172	¬	 204	Ì	 236	ì

 141	 173	­	 205	Í	 237	í

 142	 174	®	 206	Î	 238	î

 143	 175	¯	 207	Ï	 239	ï

 144	 176	°	 208	Ð	 240	ð

 145	 177	±	 209	Ñ	 241	ñ

 146	 178	²	 210	Ò	 242	ò

 147	 179	³	 211	Ó	 243	ó

 148	 180	´	 212	Ô	 244	ô

 149	 181	µ	 213	Õ	 245	õ

 150	 182	¶	 214	Ö	 246	ö

 151	 183	·	 215	×	 247	÷

 152	 184	¸	 216	Ø	 248	ø

 153	 185	¹	 217	Ù	 249	ù

 154	 186	º	 218	Ú	 250	ú

 155	 187	»	 219	Û	 251	û

 156	 188	¼	 220	Ü	 252	ü

 157	 189	½	 221	Ý	 253	ý

 158	 190	¾	 222	Þ	 254	þ

 159	 191	¿	 223	ß	 255	ÿ

These characters aren't supported by Microsoft Windows.


Conversion Functions

Asc Function

CCur Function

CDbl Function

CInt Function

CLng Function

CSng Function

CStr Function

CVar Function

CVDate Function

Format, Format$ Function

Str, Str$ Function

Val Function


Asc Function

See Also	Example

Returns a numeric value that is the ANSI code for the first character in a string expression.

Syntax

Asc(stringexpression)

Remarks

If the stringexpression argument is a zero-length String or a Null Variant (VarType 1), a run-time error will occur.


See Also

ANSI Character Set

Chr, Chr$ Function


Asc Function Example

The example uses the Asc function to return the numeric equivalent of a range of characters.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg	' Declare variables.

For I = Asc("A") To Asc("Z")	' From A through Z.

Msg = Msg & Chr(I)	' Create a string.

Next I

MsgBox Msg	' Display results.

End Sub


CVDate Function

See Also	Example

Converts an expression to a Variant of VarType 7 (Date).

Syntax

CVDate(expression)

Remarks

The argument expression must be a string expression or a numeric expression that can be interpreted as a date.  The acceptable range for date information is January 1, 100 A.D. (-657434) through December 31, 9999 A.D. (2958465).

The following table identifies the action that occurs as a result of evaluating expression.

If expression is this type	CVDate takes this action
A numeric expression	Checks range. if not in range, generates a run time error; otherwise converts expression to a date.
A string expression that looks like a date, for example,  "1 May 1992 12:00 PM"	Converts expression to a date.
A string expression that looks like a number, for example, "33664"	Converts expression to a number. Checks range.  If not in range, generates a run-time error; otherwise converts expression to a date.
Any other string expression	Generates a run-time error.
For string expressions, CVDate recognizes date formats that can be set in the International section of the WIN.INI file using the Microsoft Windows Control Panel.  However, CVDate cannot recognize a long date format if it also contains the day-of-the-week string.

If a string expression contains only numbers, CVDate may not be able to determine the correct order of day, month, and year if it is provided in a format other than one of the current WIN.INI date settings.

Note	You may be able to use the IsDate function to determine if either a numeric expression or a string expression that looks like a date can actually be converted to a date.  However, IsDate cannot determine if a string that looks like a number can be converted to a date.

Note	When converting from a number to a date, Visual Basic converts any fractional part of the number to a time of day, starting at midnight.


See Also

Data Type Conversion Functions

IsDate Function


CVDate Function Example

The example returns a Variant of VarType 7 containing the date serial for your birth date.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim BirthDate, Msg, TestDate	' Declare variables.

Msg = "Enter your birth date using any form you like."

Do

TestDate = InputBox(Msg)	' Get user date.

Loop Until IsDate(TestDate)	' Test for valid date.

BirthDate = CVDate(TestDate)	' Make Variant.

Msg = "The short form of your birth date is " & BirthDate

MsgBox Msg	' Display message.

End Sub


Data Type Conversion Functions

See Also	Example

Explicity converts expressions from one data type to another.

Syntax

CCur(expression)

CDbl(expression)

CInt(expression)

CLng(expression)

CSng(expression)

CStr(expression)

CVar(expression)

Remarks

The argument expression can be any valid string expression or numeric expression.

The following table shows which data type is returned by each data type conversion function.

Function 	From 	To

CCur	Any valid expression	Currency

CDbl	Any valid expression	Double

CInt	Any valid expression	Integer

CLng	Any valid expression	Long

CSng	Any valid expression	Single

CStr	Any valid expression	String

CVar	Any valid expression	Variant

The numeric conversion functions CCur, CDbl, CInt, CLng, and CSng explicitly control the data type of a numeric expression.  For example, you can use CCur to force currency arithmetic (which has greater precision but less range) in cases in which integer, double-precision, or single-precision arithmetic normally would occur.  CInt and CLng force integer arithmetic in cases in which currency, single-precision, or double-precision arithmetic normally would occur.  CDbl and CSng force double-precision or single-precision arithmetic in cases in which currency or integer arithmetic normally would occur.

Tip	Use these data type conversion functions to document your code to show that the result of a calculation should be expressed as a particular data type rather than the normal data type of the result.

For the CCur, CInt, CLng, and CSng functions, if expression lies outside the acceptable range, an Overflow error occurs and a message is displayed unless it is trapped in error-handling code.

Note	CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number.  When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number.  For example, 0.5 rounds to 0, and 1.5 rounds to 2.


See Also

Visual Basic Data Types

Int Function, Fix Function


Data Type Conversion Function Examples

CCur Function Example

CDbl Function Example

CInt Function Example

CLng Function Example

CSng Function Example

CStr Function Example

CVar Function Example


CCur Function Example

CCur converts a value calculated as a Double to a Currency with four decimal digits of precision to the right of the decimal place, displaying the result in conventional currency value format with two places to the right of the decimal.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Amount, Msg, Percent, SalesTax	' Declare variables.

Percent = 8.2	' Set tax percentage rate.

Msg = "What is the taxable currency amount?"

Amount = InputBox(Msg)	' Get user input.

SalesTax = CCur(Amount * (Percent * .01))	' Calculate tax.

Msg = "Tax on " & Format(Amount, "Currency")

Msg = Msg & " is " & Format(SalesTax, "Currency")

MsgBox Msg	' Display results.

End Sub


CDbl Function Example

The CDbl function converts a Currency value to a Double.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CurrVal, CurrPercent, Msg, Percent	' Declare variables.

Percent = 8.2	' Set tax rate.

Msg = "Enter a currency value."

CurrVal = CCur(InputBox(Msg))	' Get user input.

CurrPercent = CDbl(CurrVal * Percent * .01)	' Calculate value.

Msg = Percent & "% of "

Msg = Msg & Format(CurrVal, "Currency")

Msg = Msg & " is $" & CurrPercent

Msg = Msg & " expressed as a double-precision number."

MsgBox Msg	' Display results.

End Sub


CInt Function Example

The example converts an angle in radians to an angle in degrees and minutes.  The CInt function is used to convert a double-precision value to an integer value.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degs, Mins, Pi, Msg	' Declare variables.

Dim Rads, Rads2Deg, WholeDegs, WholeMins

Pi = 4 * Atn(1)	' Calculate Pi.

Rads2Degs = 180 / Pi	' Calculate conversion factor.

Msg = "Please enter an angle in radians."

Rads = InputBox(Msg)	' Get angle in radians.

Degs = Rads * Rads2Degs	' Convert radians to degrees.

Mins = Degs - Int(Degs)	' Get fractional part.

WholeMins = CInt(Mins * 60)	' Convert to between 0 and 60.

WholeDegs = Int(Degs)	' Get whole number part.

If WholeMins = 60 Then	' 60 minutes = 1 degree.

WholeDegs = WholeDegs + 1

WholeMins = 0

End If

Msg = "Angle = " & WholeDegs & " degrees, "

Msg = Msg & WholeMins & " minutes."

MsgBox Msg	' Display results.

End Sub


CLng Function Example

The example uses the CLng function to convert double-precision numbers to long integers.  It also demonstrates how CLng rounds numbers when converting.  Note that 25427.45 is rounded down to 25427, whereas 25427.55 is rounded up to 25428.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

NL = Chr(13) & Chr(10)	' Define newline.

Msg = "25427.45 rounds to " & CLng(25427.45) & "."

Msg = Msg & NL & "25427.55 rounds to "

Msg = Msg & CLng(25427.55) & "."

MsgBox Msg	' Display results.

End Sub


CSng Function Example

The example uses the CSng function to convert double-precision numbers to single-precision.  It also demonstrates how CSng rounds numbers when converting.  Note that 75.3421115 is rounded down to 75.34211, whereas 75.3421155 is rounded up to 75.34212.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(13) & Chr(10)	' Define newline.

Msg = "75.3421115 rounds to " & CSng(75.3421115)

Msg = Msg & "." & NL & "75.3421555 rounds to "

Msg = Msg & CSng(75.3421555) & "."

MsgBox Msg	' Display results.

End Sub


CStr Function Example

The example uses the CStr function to convert a Double to a String.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NumVal, StrVal	' Declare variables.

Msg = "Enter some numeric value."

NumVal = InputBox(Msg)	' Get user input.

StrVal = CStr(StrVal)	' Perform conversion.

Msg = "StrVal is a Variant containing a number that has "

Msg = Msg & "been converted to a String."

MsgBox Msg	' Display message.

End Sub


CVar Function Example

CVar takes a String value expressed in thousands, concatenates three zeros, and converts the entire expression to a Variant.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, SalesInK, TotalUnits	' Declare variables.

SalesInK = InputBox("How many thousand units did you sell?")

TotalUnits = CVar(SalesInK & "000")

Msg = "You sold " & Format(TotalUnits, "###,###") & " units."

MsgBox Msg	' Display message.

End Sub


Val Function

See Also	Example

Returns the numeric value of a string of characters.

Syntax

Val(stringexpression)

Remarks

The argument stringexpression is a sequence of characters that can be interpreted as a numeric value.  The Val function stops reading the string at the first character that it cannot recognize as part of a number.  Val also strips blanks, tabs, and line feeds from the argument string.  For example, the following returns the value 1615198:

Val("    1615 198th Street N.E.")

Symbols and characters often considered part of a numeric value, such as the dollar sign and commas, are not recognized by Val as numeric.  The Val function does recognize the radix prefixes &O (for octal) and &H (for hexadecimal).  In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")

The Val function always returns a Double.  If the result of the Val function is assigned to a variable, the Double returned by Val is forced into the data type of the variable.

Tip	If the string expression you want to convert to numbers contains only numbers, consider using one of the numeric data type conversion functions (CCur, CDbl, CInt, CLng, CSng, or CVar) to perform the conversion.  To convert a numeric value to a String or Variant, you can use the Format, CStr, or CVar function.

Note	The usefulness of the Val function is all but eliminated if you use the Variant data type for your variables.  This is because conversion back and forth between strings and numbers is accomplished automatically.


See Also

Data Type Conversion Functions

Format, Format$ Function

Str, Str$ Function


Val Function Example

The example uses the Val function to determine if the first characters in a string are a number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variables.

Dim Number As Double

Number = Val(InputBox$("Enter a number"))	' Get user input.

Msg = "The number you entered is:" & Number

MsgBox Msg	' Display message.

End Sub


Call Statement

See Also	Example

Transfers program control to a Visual Basic Sub procedure or a dynamic-link library (DLL) procedure.

Syntax 1

Call name [(argumentlist)]

Syntax 2

name [argumentlist]

Remarks

The Call statement has these parts:

Part	Description

Call	Optional keyword used to transfer program control to another procedure.

name 	Name of the procedure to call.

argumentlist	Variables, arrays, or expressions to pass to the procedure.

You are never required to use the Call keyword when calling a procedure.  If you use the Call keyword to call a procedure that requires arguments, the argument list must be enclosed in parentheses.  If you omit the Call keyword, you also must omit the parentheses around the argument list.

You can pass arguments to a procedure by reference or by value.  Values of arguments passed by reference can be altered by the procedure when the arguments are returned; Visual Basic supplies the actual address of the argument.  Arguments passed by value are assigned a temporary address and the values cannot be altered.  Arguments are passed by reference unless enclosed by parentheses or declared using the ByVal keyword.

When passing arguments to DLL procedures, you may want to pass arguments by value.  Many DLL routines don't support all Visual Basic data types and ByVal will attempt a conversion.  You can also use the ByVal keyword when you declare the DLL procedure in the Declarations section.

To pass a whole array, use the array name followed by empty parentheses.


See Also

Declare Statement


Call Statement Example

The example shows two ways to call the MessageBeep procedure in USER.EXE, a Microsoft Windows DLL.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

Sub Form_Click ()

Dim I	' Declare variable.

Call MessageBeep(0)	' Call Windows procedure.

For I = 1 To 100 : Next I	' Insert short delay between calls.

MessageBeep 0	' Call again without Call keyword.

End Sub


DoEvents Function, DoEvents Statement

Example

Causes Visual Basic to yield execution so that Microsoft Windows can process events.

Function Syntax

DoEvents( )

Statement Syntax

DoEvents

Remarks

The DoEvents function returns the number of visible forms.

DoEvents passes control to the Windows environment.  Control is not returned until the Windows environment has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

Use DoEvents to interrupt processing so the Windows environment can respond normally to other events, such as keyboard input and mouse clicks.  If parts of your code take up too much processor time, use DoEvents to relinquish control to the Windows environment.

Caution	Make sure the procedure that has given up control with DoEvents is not executed again by a different part of your program before the first DoEvents call returns; this could cause unpredictable results.  In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.


DoEvents Statement Example

In this example, DoEvents yields to the Windows environment only in the second loop, allowing keystrokes every 1000 loops.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, N	' Declare variables.

MsgBox "Choose OK, then try pressing a key."

For I = 1 To 15000	' Start first loop.

N = Int(5000 * Rnd + 1)	' Generate random number.

Next I	' Increment loop counter.

Msg = "Note that any keys you pressed weren't processed"

Msg = Msg & " until the 1st loop was finished. Now choose OK"

Msg = Msg & " and try again."

MsgBox Msg	' Display message.

For I = 1 To 15000	' Start second loop.

N = Int(5000 * Rnd + 1)	' Generate random number.

If I Mod 1000 = 0 Then DoEvents	' Yield to other events.

Next I	' Increment loop counter.

Msg = "During the second loop, your keystrokes were processed"

Msg = Msg & " each time the count was evenly divisible by 1000."

Msg = Msg & " improving the response but degrading the performance."

MsgBox Msg	' Display message.

End Sub


Do...Loop Statement

See Also	Example

Repeats a block of statements while a condition is true or until a condition becomes true.

Syntax 1

Do [{While | Until} condition]

[statementblock]

[Exit Do]

[statementblock]

Loop

Syntax 2

Do

[statementblock]

[Exit Do]

[statementblock]

Loop [{While | Until} condition]

Remarks

The Do...Loop statement has these parts:

Part	Description

Do 	Must be the first statement in a Do...Loop control structure.

While	Indicates that the loop is executed while condition is true.

Until	Indicates that the loop is executed until condition is true.

condition	Numeric or string expression that evaluates true (nonzero) or false (0 or Null).

statementblock	Program lines between the Do and Loop statements that are repeated while or until condition is true.

Exit Do	Only used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop.  Any number of Exit Do statements may be placed anywhere in the Do...Loop.  Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.

Loop	Ends a Do...Loop.

When Do...Loop statements are nested, control is transferred to the Do...Loop that is one nested level above the loop in which the Exit Do occurs.


See Also

Exit Statement

While...Wend Statement


Do...Loop Statement Example

The example creates an infinite Do...Loop that can be exited only if the user enters a number in a range.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Reply	' Declare variable.

Do

Reply = InputBox("Enter a number greater than 1 and less than 9.")

If Reply > 1 And Reply < 9 Then	' Check range.

Exit Do	' Exit Do Loop.

End If

Loop

End Sub

Alternatively, the same thing can be accomplished by incorporating the range test in the Do...Loop as follows:

Sub Form_Click ()

Dim Reply	' Declare variable.

Do

Reply = InputBox("Enter a number greater than 1 and less than 9.")

Loop Until Reply > 1 And Reply < 9

End Sub


End Statement

See Also	Example

Ends a Visual Basic procedure or block.

Syntax

End [{Function | If | Select | Sub | Type}]

Remarks

You can use the End statement in any of the following ways:

Statement	Description

End Function	Ends a Function procedure definition.  You must use End Function with Function.  Automatically added when you create a new Function procedure.

End If	Ends a block If...Then statement.  Required to end a block
If...Then...Else.

End Select	Required to end a Select Case block.

End Sub	Required to end a Sub procedure.  Automatically added when you create a new Sub procedure.

End Type	Required to end a user-defined type definition (Type statement).

End	By itself, terminates program execution.  Equivalent to choosing End from the  Run menu.  Never required and may be placed anywhere in a procedure.

While the End statement is never required to terminate program execution, it is generally accepted as good programming practice since it closes files, destroys forms, and clears the value of all variables.


See Also

Exit Statement

Function Statement

If...Then...Else Statement

Select Case Statement

Stop Statement

Sub Statement

Type Statement


End Statement Example

The example uses End to end code execution, to end a Select Case block, and to end a Sub procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim UserInput	' Declare variable.

Do	' Set up infinite loop.

UserInput = UCase(InputBox("Enter A or X to end program."))

Select Case UserInput	' Evaluate input.

Case "A" : MsgBox "You entered 'A'."

Case "X" : End	' End execution if user entered X.

Case Else : MsgBox "You made an invalid choice. Try again."

End Select	' End Select Case block.

Loop

End Sub	' End Sub procedure.


Exit Statement

See Also	Example

Exits a Do...Loop, a For...Next loop, a Function procedure, or a Sub procedure.

Syntax

Exit { Do | For | Function | Sub }

Remarks

You can use the Exit statement in any of the following ways:

Statement	Description

Exit Do	Provides a way to exit a Do...Loop statement.  It can be used only inside a Do...Loop statement.  Exit Do transfers control to the statement following the Loop statement.  When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop in which it occurs.

Exit For	Provides a way to exit a For...Next loop.  It can be used only in a For...Next loop.  Exit For transfers control to the statement following the Next statement.  When used within nested For...Next loops, Exit For transfers control to the loop that is one nested level above the loop in which it occurs.

Exit Function	Immediately exits the Function procedure in which it appears.  Program execution continues with the statement following the statement that has called the Function.

Exit Sub	Immediately exits the Sub procedure in which it appears.  Program execution continues with the statement following the statement that has called the Sub.

Do not confuse Exit statements with End statements.  Exit does not define the end of a structure.


See Also

Do...Loop Statement

End Statement

For...Next Statement

Function Statement

Stop Statement

Sub Statement


Exit Statement Example

The example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Num	' Declare variables.

Do	' Set up infinite loop.

For I = 1 To 1000

Num = Int(Rnd * 100)	' Generate random numbers.

Select Case Num	' Evaluate random number.

Case 7 : Exit For	' If 7, exit For...Next.

Case 29 : Exit Do	' If 29, exit Do...Loop.

Case 54 : Exit Sub	' If 54, exit Sub procedure.

End Select

Next I

Loop

End Sub


For...Next Statement

See Also	Example

Repeats a group of instructions a specified number of times.

Syntax

For counter = start To end [ Step increment ]

[statementblock]

[Exit For]

[statementblock]

Next [counter [, counter][, ...]]

Remarks

The For...Next statement has these parts:

Part	Description

For	Begins a For...Next loop control structure.  Must appear before any other part of the structure.

counter	Numeric variable used as the loop counter.  The variable cannot be an array element or a record element.

start	Initial value of counter.

To	Separates start and end values.

end	Final value of counter.

Step	Indicates that increment is explicitly stated.

increment	Amount counter is changed each time through the loop.  If you do not specify Step, increment defaults to one.

statementblock	Program lines between For and Next that are executed the specified number of times.

Exit For	Only used within a For...Next control structure to provide an alternate way to exit.  Any number of Exit For statements may be placed anywhere in the For...Next loop.  Often used with the evaluation of some condition (for example, If...Then), Exit For transfers control to the statement immediately following the Next

Next	Ends a For...Next loop.  Causes increment to be added to counter.

The Step value controls loop execution as follows:

When step is	Loop executes if

Positive or 0	counter <= end

Negative	counter >= end

Once the loop has been entered and all the statements in the loop have executed, Step is added to counter.  At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute in the first place), or the loop is exited and execution continues with the statement following the Next statement.

Tip	Changing the value of counter while inside a loop can make the program more difficult to read and debug.

You can nest For...Next loops by placing one For...Next loop within another.  Give each loop a unique variable name as its counter.  The following construction is correct:

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

...

Next K

Next J

Next I

A Next statement with the form Next K, J, I is equivalent to the following sequence of statements:

Next K

Next J

Next I

Note	If you omit the variable in a Next statement,  the value of Step increment is added to the variable associated with the most recent For statement.  If a Next statement is encountered before its corresponding For statement, an error occurs.


See Also

Do...Loop Statement

Exit Statement

While...Wend Statement


For...Next Statement Example

The example puts five lines of the uppercase alphabet into a message box using two nested loops.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL, Rep	' Declare variables.

NL = Chr(13) & Chr(10)	' Define newline.

For Rep = 5 To 1 Step -1	' Set up five repetitions.

For I = Asc("A") To Asc("Z")	' Convert alpha to numbers.

Msg = Msg & Chr(I)	' Append each letter to string.

Next I

Msg = Msg & NL	' Add newline for each rep.

Next Rep

MsgBox Msg	' Display message box.

End Sub


GoSub...Return Statement

See Also	Example

Branch to, and return from, a subroutine within a procedure.

Syntax

 GoSub {linelabel | linenumber}
. . .

linelabel: or linenumber
. . .

Return

Remarks

The GoSub...Return statement has these parts:

Part	Description

GoSub	Causes program flow to branch to a subroutine within a procedure.

linelabel	Label that marks the first line of the subroutine.  The linelabel must begin with an alphabetic character, must end with a colon, must be 40 characters or less, and must not be a Visual Basic keyword.  Each linelabel must be unique in the module in which it is used.  Line labels are not case-sensitive and may begin in any column as long as they are the first nonblank characters on the line.

linenumber	Line number that marks the first line of the subroutine.  The linenumber can be any number of 40 characters or less, can contain only decimal digits (0-9), and must not end with a colon.  Each linenumber must be unique in the module in which it appears.  Line numbers may begin in any column as long as they are the first nonblank characters.  If linenumber is greater than 65,529, the Erl function cannot properly report the line number where an error has occurred.

Return	Causes program flow to return to the statement following the GoSub statement.  For every GoSub statement there must be an associated Return.

GoSub and Return can be used anywhere in a procedure, but the GoSub and corresponding Return must occur within the same procedure.  A subroutine can contain more than one Return statement, but the first Return statement encountered causes program flow to branch back to the statement immediately following the most recently executed GoSub statement.

Note	You cannot enter or exit Sub procedures with GoSub...Return.

Caution	Subroutines that call themselves (recursive subroutines) can easily run out of stack space and halt your program unexpectedly.


See Also

End Statement

GoTo Statement

On...GoSub Statement, On...GoTo Statement

Sub Statement


GoSub...Return Statement Example

The example uses GoSub to call a subroutine from within a Sub procedure.  Notice that the GoTo branch avoids the subroutine.  This kind of branching is generally considered to be poor programming technique.  To avoid this kind of branching, turn subroutines into Sub procedures.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Num	' Declare variable.

Num = InputBox("Type a number.")

GoSub Routine	' Branch to subroutine.

GoTo Nextpart	' Branch around subroutine.

Routine:	' Start of subroutine.

Num = Num / 2

Return	' Return from subroutine.

Nextpart:	' Continuation of program.

Msgbox "Half of your number is " & Num

End Sub


GoTo Statement

See Also	Example

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo { linelabel | linenumber}

Remarks

The GoTo statement has these parts:

Part	Description

GoTo	Causes program execution to continue at another place within a procedure.

linelabel	Label that marks the line to execute next.  The linelabel must begin with an alphabetic character, must end with a colon, must be 40 characters or less, and must not be a Visual Basic keyword.  Each linelabel must be unique in the module in which it is used.  Line labels are not case-sensitive and may begin in any column as long as they are the first nonblank characters on the line.

linenumber	Line number that marks the line to execute next.  The linenumber can be any number of 40 characters or less, can contain only decimal digits (0-9), and must not end with a colon.  Each linenumber must be unique in the module in which it appears.  Line numbers may begin in any column as long as they are the first nonblank characters.  If linenumber is greater than 65,529, the Erl function cannot properly report the line number where an error has occurred.

GoTo can branch only to lines within the procedure where it appears.

Note	Programs with many GoTo statements can be difficult to read and debug.  Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.


See Also

Do...Loop Statement

For...Next Statement

GoSub...Return Statement

If...Then...Else Statement

Select Case Statement


GoTo Statement Example

The example uses GoTo to branch around a subroutine.  This kind of branching is generally considered to be poor programming technique.  To avoid this kind of branching, turn subroutines into Sub procedures.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Num	' Declare variable.

Num = InputBox("Type a number.")

GoSub Routine	' Branch to subroutine.

GoTo Nextpart	' Branch around subroutine.

Routine:	' Start of subroutine.

Num = Num / 2

Return	' Return from subroutine.

Nextpart:	' Continuation of program.

Msgbox "Half of your number is " & Num

End Sub


If...Then...Else Statement

See Also	Example

Allows conditional execution, based on the evaluation of an expression.

Syntax 1

If condition Then thenpart  [Else elsepart]

Syntax 2

If condition1  Then
[statementblock-1]
[ElseIf condition2 Then
[statementblock-2] ]
[Else
[statementblock-n] ]
End If

Remarks

Syntax 1

The single-line form is often useful for short, simple conditional tests.  Syntax 1 has these parts:

Part	Description

If	Begins the simple If...Then control structure.

condition	One of two types of expressions:

A numeric or string expression that evaluates true (nonzero) or false (0 and Null).

A single expression of the form TypeOf object Is objecttype.  The object is a form or control variable and objecttype is any one of the recognized Visual Basic object types.

Then	Identifies actions to be taken if condition is satisfied.

thenpart	Statements or branches performed when condition is true or if object is of the type specified by objecttype.

Else	Identifies actions taken if condition is not satisfied.  If the Else clause is not present, control passes to the next statement in the program.

elsepart	Statements or branches performed when condition is false or object is not of the specified objecttype.

The thenpart and the elsepart fields both have this syntax:

{statements | [GoTo] linenumber | GoTo linelabel }

The thenpart and elsepart syntax has these parts:

Part	Description

statements	One or more Visual Basic statements, separated by colons.

GoTo	Keyword that is optional with a line number but required with a line label.

linenumber	A valid program line number.

linelabel	A valid program line label.

Note	You can have multiple statements with a condition, but they must be on the same line and separated by colons, as in the following statement:

If A > 10 Then A = A + 1 : B = B + A : C = C + B

Syntax 2

The block form of If...Then...Else provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.  Syntax 2 has these parts:

Part	Description

If	Keyword that begins the block If...Then decision control structure.

condition1	Same as condition used in the single-line form shown above.

Then	Keyword used to identify the actions to be taken if a condition is satisfied.

statementblock-1	One or more Visual Basic statements executed if condition1 is true or if object is of the type specified by objecttype.

ElseIf	Keyword indicating that alternative conditions must be evaluated if condition1 is not satisfied.

condition2	Same as condition used in the single-line form shown above.

statementblock-2	One or more Visual Basic statements executed if condition2 is true or if object is of the type specified by objecttype.

Else	Keyword used to identify the actions taken if none of the previous conditions are satisfied.

statementblock-n	One or more Visual Basic statements executed if condition1 and condition2 are both false or if object is not of the type specified by objecttype

End If	Keyword that ends the block form of the If...Then.

In executing a block If, Visual Basic tests condition1, the first numeric expression or TypeOf expression.  If the expression is true or if object is of the type specified by objecttype, the statements following Then are executed.

If the first expression is false or if object is not of the type specified by objecttype, Visual Basic begins evaluating each ElseIf condition in turn.  When Visual Basic finds a true condition or an object that is of the type specified by objecttype, the statements immediately following the associated Then are executed.  If none of the ElseIf conditions is true or no object is of the type specified in its associated objecttype, the statements following the Else are executed.  After executing the statements following Then or Else, the program continues with the statement following End If.

The Else and ElseIf clauses are both optional.  You can have as many ElseIf clauses as you like in a block If, but none can appear after an Else clause.  Any of the statement blocks can contain nested block If statements.

Visual Basic looks at what appears after the Then keyword to determine whether or not an If statement is a block If.  If anything other than a comment appears after Then, the statement is treated as a single-line If statement.

A block If statement must be the first statement on a line.  The Else, ElseIf, and End If parts of the statement can have only a line number or line label in front of them.  The block If must end with an End If statement.

Standard numeric and string expressions cannot be evaluated in the same conditional expression as expressions that use the form If TypeOf object Is objecttype.  Use a separate ElseIf block for objects.

For example:

If a > 1 And a <= 100 Then

...

ElseIf TypeOf controlVar Is ListBox Then

...

End If

Tip	Select Case may be more useful when evaluating a single expression that has several possible actions.


See Also

Select Case Statement


If...Then...Else Statement Example

The example illustrates the various forms of the If...Then...Else syntax.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim X, Y	' Declare variables.

X = InputBox("Enter a number greater than 0 and less than 1000.")

If X < 10 Then

Y = 1	' 1 digit.

ElseIf X < 100 Then

Y = 2	' 2 digits.

Else

Y = 3	' 3 digits.

End If

If Y > 1 Then Unit = " digits." Else Unit = " digit."

MsgBox "The number you entered has " & Y & Unit

End Sub


On...GoSub, On...GoTo Statements

See Also	Example

Branch to one of several specified lines, depending on the value of an expression.

Syntax 1

On expression GoSub destinationlist

Syntax 2

On expression GoTo destinationlist

Remarks

The On...GoSub, On...GoTo syntax has these parts:

Part	Description

On	Begins the On...GoSub or On...GoTo control structure.

expression	Any numeric expression that evaluates to a value between 0 and 255, inclusive.  (The expression is rounded to an integer value before the On...GoSub or On...GoTo statement is evaluated.)  The value of expression determines which of the lines in destinationlist the program branches to.

GoSub	Causes program flow to branch to a subroutine within a procedure.

GoTo	Causes program execution to continue at another place within a procedure.

destinationlist	List of line numbers and line labels separated by commas..

If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

Value	Result

Equal to 0	Program control drops to the next statement.

Greater than number of items in list	Program control drops to the next statement.

Negative 	Illegal function call error is generated.

Greater than 255	Illegal function call error is generated.

You can mix line numbers and line labels in the same list.  The number of line labels and line numbers you can use with On...GoSub and On...GoTo is limited only by the number you can physically fit on a single line.

Tip	Select Case provides more structure and a more flexible way to perform multiple branching.


See Also

GoSub...Return Statement

GoTo Statement

Select Case Statement


On...GoSub, On...GoTo Statement Example

The example uses On...GoSub to branch to one of two subroutines depending on user input.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, N	' Declare variables.

N = InputBox("Enter a number greater than 0 and less than 3.")

Msg = "You didn't follow directions."	' Error message.

On N GoSub Chose1, Chose2	' Choose subroutine.

MsgBox Msg	' Display results.

End

Chose1:

Msg = "You chose 1." : Return

Chose2:

Msg = "You chose 2." : Return

End Sub


Select Case Statement

See Also	Example

Executes one of several statement blocks depending on the value of an expression.

Syntax

Select Case testexpression

[Case expressionlist1

[statementblock-1] ]

[Case expressionlist2

[statementblock-2] ]

[Case Else

[statementblock-n] ]

End Select

Remarks

The Select Case syntax has these parts:

Part	Description

Select Case	Begins the Select Case decision control structure.  Must appear before any other part of the Select Case structure.

testexpression	Any numeric or string expression.  If testexpression matches the expressionlist associated with a Case clause, the statementblock following that Case clause is executed up to the next Case clause, or for the final one, up to the End Select.  Control then passes to the statement following End Select.  If testexpression matches more than one Case clause, only the statements following the first match are executed.

Case	Sets apart a group of Visual Basic statements to be executed if an expression in expressionlist matches testexpression.

expressionlist	The expressionlist consists of a comma-delimited list of one or more of the following forms.

expression

expression To expression

Is compare-operator expression

statementblock	Elements statementblock-1 to statementblock-n consist of any number of Visual Basic statements on one or more lines.

Case Else	Keyword indicating the statementblock to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections.  When there is no Case Else statement and no expression listed in the Case clauses matches testexpression, program execution continues at the statement following End Select.

End Select	Ends the Select Case.  Must appear after all other statements in the Select Case control structure.

The argument expressionlist has these parts:

Part	Description

expression	Any numeric or string expression.  The type of the expression must be compatible with the type of testexpression.  (The type of the expression will be coerced to the same type as testexpression.  For example, if testexpression is an integer, expressionlist can contain a double-precision expression, but it will be coerced to an integer.)

To	Keyword used to specify a range of values. If you use the To keyword to indicate a range of values, the smaller value must precede To.

Is	Keyword used with comparison operators to specify a range of values.  If not provided, it is automatically inserted.

compare-operator	Any valid comparison operator, except Is and Like.

Note	Do not  confuse the Is comparison operator with the Is keyword used in the Select Case statement.  They are not the same.

Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values.

You can use multiple expressions or ranges in each Case clause.  For example, the following line is valid:

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber

You also can specify ranges and multiple expressions for character strings.  In the following example, Case matches strings that are exactly equal to everything,strings that fall between nuts and soup in alphabetical order, and the current value of TestItem$:

Case "everything", "nuts" To "soup", TestItem$

Select Case statements can be nested.  Each Select Case statement must have a matching End Select statement.


See Also

If...Then...Else Statement

On...GoSub, On...GoTo Statements

Option Compare Statement


Select Case Statement Example

The example uses Select Case to decide what action to take based on user input.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, UserInput	' Declare variables.

Msg = "Please enter a letter or number from 0 through 9."

UserInput = InputBox(Msg)	' Get user input.

If Not IsNumeric(UserInput) Then	' Is it letter or number?

If Len(UserInput) <> 0 Then

Select Case Asc(UserInput)	' If it's a letter.

Case 65 To 90	' Must be uppercase.

Msg = "You entered the uppercase letter '"

Msg = Msg & Chr(Asc(UserInput)) & "'."

Case 97 To 122	' Must be lowercase.

Msg = "You entered the lower-case letter '"

Msg = Msg & Chr(Asc(UserInput)) & "'."

Case Else	' Must be something else.

Msg = "You did not enter a letter or a number."

End Select

End If

Else

Select Case CDbl(UserInput)	' If it's a number.

Case 1, 3, 5, 7, 9	' It's odd.

Msg = UserInput & " is an odd number."

Case 0, 2, 4, 6, 8	' It's even.

Msg = UserInput & " is an even number."

Case Else	' Out of range.

Msg = "You entered a number outside "

Msg = Msg & "the requested range."

End Select

End If

MsgBox Msg	' Display message.

End Sub


Shell Function

Example

Runs an executable program.

Syntax

Shell(commandstring [, windowstyle])

Remarks

The Shell function has these parts:

Part	Description

commandstring	Name of the program to execute and any required arguments or command line switches.  If the program name in commandstring doesn't include a .COM, .EXE, .BAT, or .PIF file extension, an error occurs.

windowstyle	Number corresponding to the style of the window in which the program is to be executed.  If windowstyle is omitted, the progam is opened minimized with focus, the same as windowstyle = 2.

The following table identifies the values for windowstyle and the resulting style of window:

Value	Window style

1, 5, 9	Normal with focus.

2	Minimized with focus (default).

3	Maximized with focus.

4, 8	Normal without focus.

6, 7	Minimized without focus.

If the Shell function successfully executes the named program, it returns the 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.  That means that you cannot depend on a program started with Shell to be finished executing before the code following the Shell function in your Visual Basic application is executed.


Shell Function Example

The example uses Shell to leave the current application and run the Calculator program included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to either quit the Calculator or add some numbers, depending on the user's choice.  AppActivate is used to move the focus between Microsoft Visual Basic and the Calculator.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, X, Msg	' Declare variables.

AppActivate "Microsoft Visual Basic"	' Change focus to Visual Basic.

SendKeys "%{ }{Down 3}{Enter}", True	' Minimize Visual Basic.

X = Shell("Calc.exe", 1)	' Shell Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	' to add each value of I.

SendKeys "=", True	' Get grand total.

AppActivate "Microsoft Visual Basic"	' Return focus to Visual Basic.

Msg = "Choose OK to close the Calculator.

MsgBox Msg	' Display OK prompt.

AppActivate "Calculator"	' Return focus to Calculator.

SendKeys "%{F4}", True	' Alt+F4 to close Calculator.

AppActivate "Microsoft Visual Basic"	' Return focus to Visual Basic.

SendKeys "%{ }{Enter}", True	' Restore Visual Basic to size.

End Sub


Stop Statement

See Also	Example

Suspends execution of the running Visual Basic code.

Syntax

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend program execution.

The Stop statement suspends program execution, but unlike End, doesn't close files or clear variables.  To continue a program suspended by the Stop statement, choose Continue from the Run menu or Single Step from the Debug menu.

Under certain circumstances, you also may be able to restart program execution immediately after the Stop statement by entering a statement in the Debug window.  For example, if the Stop statement occurs in an error handler, you can enter a Resume statement in the Debug window to resume program execution.  If the Stop statement occurs in a subroutine (not a Sub procedure), you can enter a Return statement in the Debug window to continue the program.

If you don't use line numbers or line labels, you can specify which line you want to have executed next by using Set Next Statement from the Debug menu and then choosing Continue or Single Step to begin execution.  If you do use line numbers or line labels, you can continue a suspended program at a specific point by entering a GoTo statement with an appropriate line number or line label in the Debug window.


See Also

End Statement


Stop Statement Example

For each step through this For...Next loop, Stop suspends execution.  To resume program execution, choose Continue from the Run menu.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

For I = 1 To 10	' Start For...Next loop.

Debug.Print I	' Print I to Debug window.

Stop	' Stop each time through.

Next I

End Sub


While...Wend Statement

See Also	Example

Executes a series of statements in a loop as long as a given condition is true.

Syntax

While condition
[statementblock]

Wend

The While...Wend statement has these parts:

Part	Description

While	Begins the While...Wend loop control structure.

condition	Any numeric or string expression that evaluates true (nonzero) or false (0 and Null).  If condition is true, all statements in statementblock are executed until the Wend statement is encountered.  Control then returns to the While statement and condition is again checked.  If condition is still true, the process is repeated.  If it is not true, execution resumes with the statement following the Wend statement.

statementblock	Any number of Visual Basic statements on one or more lines.

Wend	Ends the While...Wend.

Remarks

While...Wend loops can be nested to any level.  Each Wend matches the most recent While.

Caution	Do not branch into the body of a While...Wend loop without executing the While statement.  Doing so may cause run-time errors or program problems that are difficult to locate.

Tip	The Do...Loop statement provides more structure and a more flexible way to perform looping.


See Also

Do...Loop Statement


While...Wend Statement Example

The example uses While...Wend in a sorting routine.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const MAX = 5	' Declare constant.

Dim Exchange, I, Msg, NL, Temp	' Declare variables.

Static A(MAX)	' Declare an array.

NL = Chr(13) & Chr(10)	' Define newline.

A(1) = "New York"	' Put data in array in no

A(2) = "Paris"	' particular order so it

A(3) = "Chicago"	' can be sorted.

A(4) = "London"

A(5) = "Berlin"

Exchange = True	' Force 1st pass through array.

While Exchange	' Sort until no elements are

Exchange = False	' exchanged.

' Compare array elements by pairs.  When two are exchanged,

' force another pass by setting exchange to TRUE.

For I = 2 To MAX

If A(I - 1) > A(I) Then

Exchange = True	' Make swap.

Temp = A(I): A(I) = A(I - 1): A(I - 1) = Temp

End If

Next I

Wend

Msg = "Sorted order: " & NL & NL	' Create message that shows

For I = 1 To MAX	' sorted order of array

Msg = Msg & A(I) & NL	' contents.

Next I

MsgBox Msg	' Display message.

End Sub


Visual Basic Data Types

See Also

The following table shows the fundamental data types supported by Visual Basic, and the type-declaration suffix, storage size, and range of each data type.

Data type	Suffix	Storage size	Range
Integer	%	2 bytes	-32,768 to 32,767.
Long (long integer)	&	4 bytes	-2,147,483,648 to 2,147,483,647.
Single (single-precision floating-point)	!	4 bytes	-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
Double (double-precision floating-point)	#	8 bytes	-1.79769313486232E308 to  -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency (scaled integer)	@	8 bytes	-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
String	$	1 byte per character	0 to approximately 65,500 bytes. (Some storage overhead is required.)
Variant	None	As appropriate	Any numeric value up to the range of a Double or any character text.
User-defined (using Type)	None	Number required by elements	The range of each element is the same as the range of its fundamental data type, listed above.


See Also

Currency Data Type

Double Data Type

Integer Data Type

Long Data Type

Single Data Type

String Data Type

Type Statement

Variant Data Type


Integer Data Type

See Also

Integer variables are stored as 16-bit numbers (2 bytes) ranging in value from -32,768 to 32,767.  The type-declaration character for an Integer is % (ANSI character 37).

In addition to representing numbers in this range, Integers can represent Boolean values (values that can have only one of two states).  For Boolean values, -1 represents true and 0 represents false.  You can also use the Visual Basic reserved words True and False, which return -1 and 0, respectively.

You can also use Integers to represent enumerated values.  An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used.  Enumerated values provide a convenient way to select among a known number of choices.


See Also

Long Data Type

Visual Basic Data Types


Long Data Type

See Also

Long (long integer) variables are stored as signed 32-bit numbers (4 bytes) ranging in value from -2,147,483,648 to 2,147,483,647.  The type-declaration character for a Long is & (ANSI character 38).


See Also:

Integer Data Type

Visual Basic Data Types


Single Data Type

See Also

Single (single-precision floating-point) variables are stored as 32-bit numbers (4 bytes) ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values.  The type-declaration character for a Single is ! (ANSI character 33).

Note	Single-precision floating-point numbers are stored in memory using IEEE 32-bit floating-point format.  Each floating-point value consists of three parts: the sign, the exponent, and the mantissa.  In a single-precision number, the sign takes 1 bit, the exponent takes 8 bits, and the mantissa uses the remaining 23 bits plus an additional implied bit.


See Also

Double Data Type

Visual Basic Data Types


Double Data Type

See Also

Double (double-precision floating-point) variables are stored as 64-bit numbers (8 bytes) ranging in value from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values.  The type-declaration character for a Double is # (ANSI character 35).

Note	Double-precision floating-point numbers are stored in memory using IEEE 64-bit floating-point format. Each floating-point value consists of three parts: the sign, the exponent, and the mantissa.  In a double-precision number, the sign takes 1 bit, the exponent takes 11 bits, and the mantissa uses the remaining 52 bits plus an additional implied bit.


See Also

Single Data Type

Visual Basic Data Types


Currency Data Type

See Also

Currency variables are stored as 64-bit numbers (8 bytes) in a two's complement integer format, and are scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right.  This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807.  The type-declaration character for a Currency variable is @ (ANSI character 64).

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.


See Also

Long Data Type

Visual Basic Data Types


String Data Type

See Also

There are two kinds of strings:

Variable-length strings, which can contain up to approximately 65,500 characters.  Because some storage overhead is required, a string can't actually be 64K long.

Fixed-length strings, which contain a declared number of characters (less than 64K).

The type-declaration character for a String is $ (ANSI character 36).  The codes for String characters range from 0 to 255.  String characters used by all applications designed for Microsoft Windows consist of ANSI characters.  The first 128 characters (0-127) correspond to the letters and symbols on a standard U.S. keyboard.  These first 128 characters are the same as those defined by the ASCII character set.  The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


See Also

Variant Data Type

Visual Basic Data Types


Variant Data Type

See Also

The Variant data type is the default for Visual Basic [image] the data type that all variables become if they are not explicitly declared to be of some other type (using Dim, Global, or Static).  The Variant data type has no type-declaration character.

The Variant is a special data type that can contain numeric, string, or date data as well as the special values Empty and Null.  You can determine how the data in a Variant is treated by using the VarType function.  The following table illustrates the return value of the VarType function and the corresponding interpretation of the contents of the Variant:

Return value	Interpretation of Variant
0	Empty (uninitialized)
1	Null (no valid data)
2	Integer
3	Long (long integer)
4	Single (single-precision floating-point)
5	Double (double-precision floating-point)
6	Currency (scaled integer)
7	Date
8	String
Numeric data can be any integer or real number value ranging from -1.797693134862315D308 to -4.94066D-324 for negative values and from 4.94066D-324 to 1.797693134862315D308 for positive values.  Generally, numeric Variant data is maintained in its original fundamental data type within the Variant.  For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as if it were an Integer.  However, if an arithmetic operation is performed on a Variant containing an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type.  An Integer is promoted to a Long, and a Long and a Single are promoted to a Double.  An Overflow error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

Always use the Variant data type when the data could contain date information, Empty, or a Null.  You can also use the Variant data type in place of any fundamental data type to work with data in a more flexible way.  If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context.  For example:

Dim MyVar As Variant

MyVar = 98052

In the example shown above, MyVar contains a numeric representation [image] the actual value 98052.  Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers.  If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric data type, the result is an arithmetic sum.  See the information about addition and concatenation operators for complete information on how to use them with Variant data.

The value Empty denotes a Variant variable that hasn't been initialized.  A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string if it is used in a string context.

Don't confuse Empty with Null.  Null indicates that the Variant variable intentionally contains no valid data.


See Also

+ Operator

& Operator

VarType Function

Visual Basic Data Types


Any Data Type

The Any data type is used only to suppress type checking of arguments passed to dynamic-link library (DLL) procedures.


User-Defined Data Type

See Also

Any data type that you define using the Type reserved word.  User-defined data types can contain one or more elements of any fundamental Visual Basic data type.


See Also

Type Statement

Visual Basic Data Types


Date, Date$ Functions

See Also	Example

Returns the current system date.

Syntax

Date[$]

Remarks

Date returns a Variant of VarType 7 (Date) containing a date stored internally as a Double.

Date$ returns a 10-character string of the form mm-dd-yyyy, where mm is the month (01-12), dd is the day (01-31), and yyyy is the year (1980-2099).

The return value of the Date$ function is equivalent to:

Format$(Now,"mm-dd-yyyy")

To set the system date, use the Date[$] statement.


See Also

CVDate Function

Date, Date$ Statements

Format, Format$ Functions

Now Function

Time, Time$ Functions

Time, Time$, Statements


Date, Date$ Functions Example

The example uses the Date function to provide the default date for the input box when prompting the user for a new date. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Default, Msg, NewDate	' Declare variables.

Msg = "Enter a new date in the form mm-dd-yyyy"

Default = Date	' Current date.

NewDate = InputBox(Msg, "", Default)	' Get user input.

If Len(NewDate) > 0 Then	' Check if valid.

Date = NewDate	' Set date.

Msg = "System date set to "

Msg = Msg & Format(DateValue(NewDate), "dddd, mmmm d, yyyy")

Else

Msg = "You did not enter a valid date."

End If

MsgBox Msg	' Display message.

End Sub


Date, Date$ Statements

See Also	Example

Sets the current system date.

Syntax

Date[$] = expression

Remarks

For the Date statement, expression must be a String formatted as a date or a Variant of VarType 7 (Date) or VarType 8 (String).  If expression is a String (or a Variant of VarType 8) that contains only numbers delimited by valid date separators, Date recognizes the order for month, day, and year according to the Short Date format in the International section of the Windows Control Panel.  Date also recognizes unambiguous dates that contain month names, either in long or abbreviated form.  For example, in addition to recognizing 12/30/1991 and 12/30/91, Date recognizes December 30, 1991; Dec 30, 1991; 30-Dec-1991; and 30 December 91.  If expression is not already a Variant of VarType 7, Date attempts to convert it.  If it can't be converted to a date from January 1, 1980 through December 31, 2099, an error occurs.

For Date$, expression must have one of the following forms, where mm (01-12) and dd (01-31) are the month and day and yy or yyyy (1980-2099) is the year:

mm-dd-yy

mm-dd-yyyy

mm/dd/yy

mm/dd/yyyy

If you use the Date[$] statement to set the date with versions of MS-DOS earlier than 3.3, the change remains in effect only until you change it again or turn off your computer.  Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off.  However, to permanently change the date on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action.  Refer to the documentation for your particular system.


See Also

Date, Date$ Functions

Time, Time$ Functions

Time, Time$ Statements


Date, Date$ Statements Example

The example uses the Date statement to set the computer system date to a new date entered by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Default, Msg, NewDate	' Declare variables.

Msg = "Enter a new date in the form mm-dd-yyyy"

Default = Date	' Current date.

Newdate = InputBox(Msg, "", Default)	' Get user input.

If Len(Newdate) > 0 Then	' Check if valid.

Date = Newdate	' Set date.

Msg = "System date set to "

Msg = Msg & Format(DateValue(Newdate), "dddd, mmmm d, yyyy")

Else

Msg = "You did not enter a valid date."

End If

MsgBox Msg	' Display message.

End Sub


DateSerial Function

See Also	Example

Returns the date serial for a specific year, month, and day.

Syntax

DateSerial(year,month,day)

Remarks

The DateSerial function has these parts:

Part	Description

year	A number between 100 and 9999, inclusive, or a numeric expression.

month	A number between 1 and 12, inclusive, or a numeric expression.

day	A number between 1 and 31, inclusive, or a numeric expression.

To express a specific date, such as December 31, 1991, the range of numbers for each DateSerial argument should conform to the accepted range of values for the unit.  These values are 1 through 31 for days and 1 through 12 for months.  You also can specify relative dates for each argument by using a numeric expression representing the number of days, months, or years before or after a certain date.  The following example uses expressions instead of absolute date numbers.  The DateSerial function returns a date that is the day before the first day (1 - 1) of two months before August (8 - 2) of 10 years before 1990 (1990 - 10) [image] in other words, May, 31, 1980.

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

For the argument year, values between 0 and 99, inclusive, are interpreted as the years 1900-1999.  For all other year arguments, use the complete four-digit year (for example, 1800).

The DateSerial function returns a Variant of VarType 7 (Date) containing a date that is stored internally as a double-precision number.  This number represents a date from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Negative numbers represent dates prior to December 30, 1899.

If the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an error occurs.


See Also

DateValue Function

Day Function

Month Function

Now Function

TimeSerial Function

TimeValue Function

Weekday Function

Year Function


DateSerial Function Example

In this example, the DateSerial function returns a Variant (VarType 7) containing a date created from the integer arguments.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, RelVal, UserDate, Verb	' Declare variables.

Dim Flag, DD, MM, YY, WhatDay

Flag = False

Msg = "Enter a date in form mm/dd/yyyy"

Do

UserDate = InputBox(Msg)	' Get user input.

If Len(UserDate) <> 10 Then UserDate = Format(Now, "mm/dd/yyyy")

MM = Left(UserDate, 2)	' Get month number.

If MM >= 1 And MM <= 12 Then Flag = True Else Flag = False

DD = Mid(UserDate, 4, 2)	' Get day number.

If DD >= 1 And DD <= 31 Then Flag = True Else Flag = False

YY = Right(UserDate, 4)	' Get year number.

If YY >= 1753 And YY <= 2078 Then Flag = True Else Flag = False

Loop Until Flag = True

RelVal = DateSerial(YY, MM, DD)	' Get date serial.

Select Case RelVal	' Use correct verb.

Case Is < Int(Now): Verb = " was a "

Case Is > Int(Now): Verb = " will be a "

Case Else: Verb = " is a "

End Select

WhatDay = Format(RelVal, "dddd")	' Determine day.

Msg = UserDate & Verb & WhatDay & "."

MsgBox Msg	' Display message.

End Sub


DateValue Function

See Also	Example

Returns the date represented by a String argument.

Syntax

DateValue(stringexpression)

Remarks

The argument stringexpression is a String representing a date from January 1, 100 through December 31, 9999.

If stringexpression includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date setting in the International section of the Microsoft Windows Control Panel.  DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form.  For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue recognizes December 30, 1991 and Dec 30, 1991.

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

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

The DateValue function returns a Variant of VarType 7 (Date) containing a date that is stored internally as a double-precision number.  This number represents a date from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Negative numbers represent dates prior to December 30, 1899.


See Also

DateSerial Function

Day Function

Month Function

Now Function

TimeSerial Function

TimeValue Function

Weekday Function

Year Function


DateValue Function Example

The example uses the DateValue function to convert the String provided by the user to a Variant of VarType 7 (Date).  The Variant is then used to determine the day of the week for the user-provided date.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, RelVal, UserDate, Verb	' Declare variables.

Dim Flag, DD, MM, YY, WhatDay

Msg = "Enter a date in the form mm/dd/yyyy."

UserDate = InputBox(Msg)	' Get user input.

If Len(UserDate) <> 10 Then 	' Use today's date

UserDate = Format(Now, "mm/dd/yyyy")	' if user didn't

End If	' use right format.

RelVal = DateValue(UserDate)	' Get date serial.

Select Case RelVal	' Use correct verb.

Case Is < Int(Now): Verb = " was a "

Case Is > Int(Now): Verb = " will be a "

Case Else : Verb = " is a "

End Select

WhatDay = Format(RelVal, "dddd")	' Determine day.

MsgBox UserDate & Verb & WhatDay & "."	' Display message.

End Sub


Day Function

See Also	Example

Returns an integer between 1 and 31, inclusive, that represents the day of the month for a date argument.

Syntax

Day(number)

Remarks

The argument number is any numeric expression that can represent a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Hour Function

Minute Function

Month Function

Now Function

Second Function

Weekday Function

Year Function


Day Function Example

The example uses the Day function to determine the day of the month.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim DayNum, DaySuffix	' Declare variables.

DayNum = Day(Now)	' Get the current day number.

Select Case DayNum	' Get the proper suffix

Case 1, 21, 31	' for each number.

DaySuffix = "st"

Case 2, 22

DaySuffix = "nd"

Case 3, 23

DaySuffix = "rd"

Case Else

DaySuffix = "th"

End Select

MsgBox "Today is the " & DayNum & DaySuffix & " day of the month."

End Sub


Hour Function

See Also	Example

Returns an integer between 0 and 23, inclusive, that represents the hour of the day corresponding to the time provided as an argument.

Syntax

Hour(number)

Remarks

The argument number is any numeric expression that can represent a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Day Function

Minute Function

Month Function

Now Function

Second Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Hour Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Minute Function

See Also	Example

Returns an integer between 0 and 59, inclusive, that represents the minute of the hour corresponding to the time provided as an argument.

Syntax

Minute(number)

Remarks

The argument number is any numeric expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Day Function

Hour Function

Month Function

Now Function

Second Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Minute Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Month Function

See Also	Example

Returns an integer between 1 and 12, inclusive, that represents the month of the year for a date argument.

Syntax

Month(number)

Remarks

The argument number is any numeric expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Now Function

Second Function

Weekday Function

Year Function


Month Function Example

The example uses the Month function to determine the month of the year.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim MonthNum, MonthSuffix, Msg, Serial	' Declare variables.

Serial = Now	' Get date serial number.

MonthNum = Month(Serial)	' Get current month number.

Select Case MonthNum	' Get proper suffix

Case 1	'  for each number.

MonthSuffix = "st"

Case 2

MonthSuffix = "nd"

Case 3

MonthSuffix = "rd"

Case Else

MonthSuffix = "th"

End Select

Msg = Format(Serial, "mmmm") & " is the " & MonthNum

Msg = Msg & MonthSuffix & " month of the year."

MsgBox Msg	' Display message.

End Sub


Now Function

See Also	Example

Returns a date that represents the current date and time according to the setting of the computer's system date and time.

Syntax

Now

Remarks

The Now function returns a Variant of VarType 7 (Date) containing a date and time that are stored internally as a double-precision number.  This number represents a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point represent the date; numbers to the right represent the time.

Note	When displayed directly, the Now function's return value is displayed as a string using the short date and time formats set in the Microsoft Windows Control Panel.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Month Function

Second Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Now Function Example

In this example, the Now function returns the current date as a Variant of VarType 7 (Date) containing a date.  The Format function formats the date as a long date including the day and date.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Today	' Declare variable.

Today = Now	' Get current date and time.

MsgBox "Today is " & Format(Today, "dddd, mmmm dd, yyyy") & "."

End Sub


Second Function

See Also	Example

Returns an integer between 0 and 59, inclusive, that represents the second of the minute for a time argument.

Syntax

Second(number)

Remarks

The argument number is any numeric expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Day Function

Hour Function

Minute Function

Month Function

Now Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Second Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Time, Time$ Functions

See Also	Example

Returns the current system time.

Syntax

Time[$][( )]

Remarks

Time returns a Variant of VarType 7 (Date) containing a time stored internally as the fractional part of a double-precision number.

The Time$ function returns an eight-character string of the form hh:mm:ss, where hh is the hour (00-23), mm is the minute (00-59), and ss is the second (00-59).  A 24-hour clock is used; therefore, 8:00 P.M. appears as 20:00:00.

The output of the Time$ function is equivalent to:

Format$(Now,"hh:mm:ss")

To set the system time, use the Time$ statement.


See Also

Date, Date$ Functions

Date, Date$ Statements

Time, Time$ Statements

Timer Function


Time, Time$ Function Example

The example uses the Time function to provide the default time for the input box when prompting the user for a new time.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NewTime	' Declare variables.

Msg = "Enter a new time in the form hh:mm:ss"

NewTime = InputBox(Msg, "", Time)	' Get user input.

If Len(NewTime) > 0 Then	' Check if valid.

Time = NewTime	' Set time.

Msg = "System time now set to "

Msg = Msg & Time & "."	' Put time in message.

Else

Msg = "You did not enter a valid time."

End If

MsgBox Msg	' Display message.

End Sub


Time, Time$ Statements

See Also	Example

Sets the system time.

Syntax

Time[$] = expression

Remarks

For the Time statement, expression must be a String formatted as a time or a Variant of VarType 7 (Date) or of VarType 8 (String).  If expression is a String (or a Variant of VarType 8), times can be entered using a 12- or 24-hour clock.  For example, "2:24PM" and "14:24" are both valid time arguments.  If expression is not already a Variant containing a valid time, Time attempts to convert it using the time separators specified in the International section of the Windows Control Panel.  If it can't be converted to a valid time, an error occurs.

For Time$, expression must have one of the following forms, where hh is the hour (00-23), mm is the minute (00-59), and ss is the second (00-59):

Form	Description

hh	Sets the hour; the minute and the second default to 00.

hh:mm	Sets the hour and the minute; the second defaults to 00.

hh:mm:ss	Sets the hour, the minute, and the second.

A 24-hour clock is used, so 8:00 P.M. is entered as 20:00:00.

Note	If you use the Time[$] statement to set the time with versions of MS-DOS earlier than 3.3, the change remains in effect only until you change it again or turn off your computer.  Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off.  However, to permanently change the time in the CMOS RAM on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action.  Refer to the documentation for your particular system.


See Also

Date, Date$ Functions

Date, Date$ Statements

Time, Time$ Functions


Time, Time$ Statements Example

The example uses the Time statement to set the computer system time to a new time entered by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NewTime	' Declare variables.

Msg = "Enter a new time in the form hh:mm:ss"

NewTime = InputBox(Msg, "", Time)	' Get user input.

If Len(NewTime) > 0 Then	' Check if valid.

Time = NewTime	' Set time.

Msg = "System time now set to "

Msg = Msg & Time & "."	' Put time in message.

Else

Msg = "You did not enter a valid time."

End If

MsgBox Msg	' Display message.

End Sub


Timer Function

See Also	Example

Returns the number of seconds that have elapsed since 12:00 A.M. (midnight).

Syntax

Timer

Remarks

The Timer function is automatically used with the Randomize statement to generate a seed for the Rnd (random-number) function.  You can also use it to time programs or parts of programs.


See Also

Randomize Statement


Timer Function Example

The example uses the Timer function to keep track of elapsed time required to find all prime numbers between 1 and 1000.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const UNMARK = 0, MARKIT = Not UNMARK, MAXNUM = 1000

Static Mark(MAXNUM)	' Set up an array.

Dim Delta, Finish, I, Msg, N, Num, Start	' Declare variables.

Start = Timer	' Set start time.

Num = 0	' Initialize number counter.

For N = 3 To MAXNUM Step 2	' Find all primes.

If Not Mark(N) Then

Delta = 2 * N

For I = 3 * N To MAXNUM Step Delta

Mark(I) = MARKIT

Next I

Num = Num + 1

End If

Next N

Finish = Timer	' Set end time.

Msg = "The program took " & (Finish - Start)

Msg = Msg & " seconds to find "

Msg = Msg & Num & " prime numbers."

MsgBox Msg	' Display message.

End Sub


TimeSerial Function

See Also	Example

Returns the time serial for a specific hour, minute, and second.

Syntax

TimeSerial(hour, minute, second)

Remarks

The TimeSerial function has these parts:

Part	Description

hour	An hour between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.

minute	A minute between 0 and 59, inclusive, or a numeric expression.

second	A second between 0 and 59, inclusive, or a numeric expression.

To express a specific time, such as 11:59:59, the range of numbers for each TimeSerial argument should conform to the accepted range of values for the unit.  These values are 0 through 23 for hours and 0 through 59 for minutes and seconds.  You also can specify relative times for each argument by using a numeric expression representing the number of hours, minutes, or seconds before or after a certain time.  The following example uses expressions instead of absolute time numbers.  The TimeSerial function returns a time for 15 minutes before (0 - 15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, 0 - 15, 0)

The TimeSerial function returns a Variant of VarType 7 (Date) containing a time that is stored internally as a double-precision fractional number between 0 and .99999.  This number represents a time between 0:00:00 and 23:59:59, or 12:00:00 A.M.  and 11:59:59 P.M., inclusive.

If the time specified by the three arguments, either directly or by expression, falls outside the acceptable range of times, an error occurs.


See Also

DateSerial Function

DateValue Function

Hour Function

Minute Function

Now Function

Second Function

TimeValue Function


TimeSerial Function Example

In this example, the TimeSerial function creates a time serial from a number of hours, minutes, and seconds.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get the differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

TotalDiff = TimeSerial(HourDiff, MinuteDiff, SecondDiff)

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight.  That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

Msg = Msg & " Expressed in standard time notation, it becomes "

Msg = Msg & Format(TotalDiff, "hh:mm:ss") & "."

MsgBox Msg	' Display message.

End Sub


TimeValue Function

See Also	Example

Returns the time represented by a String argument.

Syntax

TimeValue(stringexpression)

Remarks

The argument stringexpression is a String representing a time from 0:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.).  You can enter valid times using a 12- or 24-hour clock.  For example, "2:24PM" and "14:24" are both valid time arguments.

If stringexpression contains date information, TimeValue doesn't return it.  However, if stringexpression includes invalid date information, an error occurs.

The TimeValue function returns a Variant of VarType 7 (Date) containing a time that is stored internally as a double-precision number between 0 and .99999.  This number represents a time between 0:00:00 and 23:59:59, or 12:00:00 A.M.  and 11:59:59 P.M., inclusive.


See Also

DateSerial Function

DateValue Function

Hour Function

Minute Function

Now Function

Second Function

TimeSerial Function


TimeValue Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Weekday Function

See Also	Example

Returns an integer between 1 (Sunday) and 7 (Saturday) that represents the day of the week for a date argument.

Syntax

Weekday(number)

Remarks

The argument number is any numeric expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Month Function

Now Function

Second Function

Year Function


Weekday Function Example

The example uses Weekday to determine the day of the week.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim DayNum, Msg	' Declare variables.

DayNum = Weekday(Now)	' Get current day of the week.

If DayNum = 1 Or DayNum = 7 Then 	' See if it's a weekend day

Msg = "Today is a weekend day."

Else	' or a weekday.

Msg = "Today is a weekday."

End If

MsgBox Msg	' Display message.

End Sub


Year Function

See Also	Example

Returns an integer between 100 and 9999, inclusive, that represents the year of a date argument.

Syntax

Year(number)

Remarks

The argument number is any numeric expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in number represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If number is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Month Function

Now Function

Second Function

Weekday Function


Year Function Example

The example uses the Year function to determine whether or not the current year is a leap year.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CurYear, LeapYear, Msg	' Declare variables.

CurYear = Year(Now)	' Get current year.

If CurYear Mod 4 = 0 And CurYear Mod 100 = 0 Then

If CurYear Mod 400 = 0 Then	' Evenly divisible by 400?

LeapYear = "is a leap year."

Else	' Not evenly divisible.

LeapYear = "is a centesimal year but not a leap year."

End If

ElseIf CurYear Mod 4 = 0 Then

LeapYear = "is a leap year."

Else

LeapYear = "is not a leap year."

End If

MsgBox "The current year, " & CurYear & ", " & LeapYear

End Sub


DDE Methods

LinkExecute Method

LinkPoke Method

LinkRequest Method

LinkSend Method


LinkExecute Method

See Also	Example

Sends a command string to the other application in a dynamic data exchange (DDE) conversation.

Syntax

control.LinkExecute cmdstring

Remarks

The LinkExecute method has these parts:

Part	Description

control	Name of the Visual Basic control involved in a DDE conversation.  The control can be any label, picture box, or text box.

cmdstring	String expression containing a command recognized by the other application.

The actual value of cmdstring will vary depending on the source applications.  For example, Microsoft Excel and Microsoft Word for Windows will accept command strings that consist of their macro commands enclosed by square brackets.  To see what command strings a source application will accept, consult documentation for that application.


See Also

LinkPoke Method

LinkRequest Method

LinkSend Method


LinkExecute Method Example

The example establishes a DDE link with Microsoft Excel, places some values into cells in the first row of a new worksheet, and charts the values.  LinkExecute sends Microsoft Excel the command to activate a worksheet, select some values, and chart them.  To try this example, Microsoft Excel must be installed and in your path.  Paste the code into the Declarations section of a form that has a text box with the default name Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const NONE = 0, LINK_MANUAL = 2	' Declare constants.

Dim Cmd, I, Q, Row, Z	' Declare variables.

Q = Chr(34)	' Define quote marks.

' Create a string containing Excel macro commands:

Cmd = "[ACTIVATE(" & Q &"SHEET1" & Q & ")]"

Cmd = Cmd & "[SELECT(" & Q & "R1C1:R5C2" & Q & ")]"

Cmd = Cmd & "[NEW(2,1)][ARRANGE.ALL()]"

If Text1.LinkMode = NONE Then

Z = Shell("Excel", 4)	' Start Excel.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = LINK_MANUAL	' Set link mode.

End If

For I = 1 To 5

Row = I	' Define row number.

Text1.LinkItem = "R" & Row & "C1"	' Set link item.

Text1.Text = Chr(64 + I)	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Text1.LinkItem = "R" & Row & "C2"	' Set link item.

Text1.Text = Row	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Next I

Text1.LinkExecute Cmd	' Execute Excel commands.

End Sub


LinkPoke Method

See Also	Example

Transfers the contents of a control to the source application in a dynamic data exchange (DDE) conversation.

Syntax

control.LinkPoke

Remarks

The control is the name of a text box, picture box, or label involved in a DDE conversation as a destination.  If control is a text box, LinkPoke transfers the current contents of the Text property to the source.  If control is a picture box, LinkPoke transfers the current contents of the Picture property to the source.  If control is a label, LinkPoke transfers the current contents of the Caption property.

Typically, information in a DDE conversation flows from source to destination.  However, LinkPoke allows a destination control to supply data to the source.  Not all source applications will accept information supplied in this way; if the source application does not accept the data, an error occurs.


See Also

LinkExecute Method

LinkRequest Method

LinkSend Method


LinkPoke Method Example

The example establishes a DDE link with Microsoft Excel, places some values into cells in the first row of a new worksheet, and charts the values.  LinkPoke sends the values to be charted to the Microsoft Excel worksheet.  To try this example, Microsoft Excel must be installed and in your path.  Paste the code into the Declarations section of a form that has a text box with the default name Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const NONE = 0, LINK_MANUAL = 2	' Declare constants.

Dim Cmd, I, Q, Row, Z	' Declare variables.

Q = Chr(34)	' Define quote marks.

' Create a string containing Excel macro commands:

Cmd = "[ACTIVATE(" & Q &"SHEET1" & Q & ")]"

Cmd = Cmd & "[SELECT(" & Q & "R1C1:R5C2" & Q & ")]"

Cmd = Cmd & "[NEW(2,1)][ARRANGE.ALL()]"

If Text1.LinkMode = NONE Then

Z = Shell("Excel", 4)	' Start Excel.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = LINK_MANUAL	' Set link mode.

End If

For I = 1 To 5

Row = I	' Define row number.

Text1.LinkItem = "R" & Row & "C1"	' Set link item.

Text1.Text = Chr(64 + I)	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Text1.LinkItem = "R" & Row & "C2"	' Set link item.

Text1.Text = Row	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Next I

Text1.LinkExecute Cmd	' Execute Excel commands.

End Sub


LinkRequest Method

See Also	Example

Asks the source in a dynamic data exchange (DDE) conversation to update the contents of a control.

Syntax

control.LinkRequest

Remarks

The control is the name of a text box, picture box, or label involved in a DDE conversation as a destination.  LinkRequest causes the source application to provide fresh data to the control, updating the Text property if the control is a text box, the Picture property if the control is a picture box, or the Caption property if the control is a label.

If the LinkMode property of the control is set to Automatic (1), the source application will automatically update the control and LinkRequest is not needed.  If the LinkMode property of the control is set to Manual (2), the source application will only update the control when  requested to with the LinkRequest method.  If the LinkMode property of the control is set to Notify (3), the source will notify the destination that data has changed by causing the LinkNotify event to occur.  The destination must then use LinkRequest to actually update the data.


See Also

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkPoke Method

LinkSend Method


LinkRequest Method Example

The example uses LinkRequest to update the contents of a text box with the values in a Microsoft Excel worksheet. To try this example, you must have Microsoft Excel running on your computer.  Place some data in the first cells in the first column in the default worksheet (called Sheet1.XLS).  Paste the code shown below into the Declarations section of a form that has a text box control called Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const NONE = 0, LINK_MANUAL = 2	' Declare constants.

If Text1.LinkMode = NONE Then	' Test link mode.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = LINK_MANUAL	' Set link mode.

Text1.LinkRequest	' Update text box

Else

If Text1.LinkItem  = "R1C1" Then

Text1.LinkItem = "R2C1"

Text1.LinkRequest	' Update text box.

Else

Text1.LinkItem = "R1C1"

Text1.LinkRequest	' Update text box.

End If

End If

End Sub


LinkSend Method

See Also	Example

Transfers the contents of a picture control to the destination application in a dynamic data exchange (DDE) conversation.

Syntax

control.LinkSend

Remarks

The control must be a picture box on a form that is acting as a source in a DDE conversation.

When other applications establish automatic links with a form in your application, Visual Basic notifies them when the contents of text boxes and labels on the form change.  However, Visual Basic does not automatically notify DDE destinations when the Picture property of a picture on a source form changes.  Because the amount of data in a picture can be very large, and because it seldom makes sense to update destinations as each pixel in the picture changes, Visual Basic requires that you use the LinkSend method to explicitly notify DDE destinations when a picture box has changed.


See Also

LinkExecute Method

LinkPoke Method

LinkRequest Method

Picture Property


LinkSend Method Example

The example allows you to draw lines in a picture box and then uses the LinkSend method to update DDE destinations with the new contents of the picture box.  Draw lines by clicking the left mouse button; update DDE destinations by clicking the right mouse button.  To try this example, place a picture box named Picture1 on a form.  Set the LinkMode property for the form to Normal.  Paste the code into the Declarations section of the form and start the Visual Basic example running by pressing F5.  Once you have the example running, start another application that can accept picture data through DDE, such as Microsoft Excel or Microsoft Word for Windows.  Create an automatic link in that other application to the picture control in your application.  For example:

Microsoft Excel 3.0 [image] create a picture and size it so you can see the data when it is sent.  Enter the following formula for the picture into the Excel Formula bar:

=Project1|Form1!Picture1

Microsoft Word for Windows 2.0 [image] insert a field.  Enter the following text into the Field Code text box, replacing the equal sign:

ddeauto project1 form1 picture1

Format the field paragraph so that line spacing is automatic.

In both cases, if the Visual Basic project name is not Project1, you should substitute the appropriate project name in the formulas above.  Likewise, if the LinkTopic property for the form is not Form1, you should substitute the contents of the LinkTopic property for Form1 in the formula above.

Note	You must start the Visual Basic example before you establish the link from the other application.

Sub Picture1_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

Dim LeftButton, RightButton	' Declare variables.

Picture1.AutoRedraw = True	' Turn on AutoRedraw.

LeftButton = Button And 1	' Define left button.

RightButton = Button And 2	' Define right button.

' Left button draws a line to the point from the previous end point.

' Right button updates DDE destinations with the contents of the picture.

If LeftButton Then

Picture1.Line -(X, Y)	' Draw lines in picture box.

ElseIf RightButton Then	' Update the picture in the

Picture1.LinkSend	' other application.

DoEvents	' Yield to Windows events.

End If

End Sub


Const Statement

See Also	Example

Declares symbolic constants for use in place of values.

Syntax

[Global] Const constantname = expression [, constantname = expression] . . .

Remarks

The Const statement has these parts:

Part	Description

Global	Reserved word that can precede Const in modules to declare constants that can be referred to by all procedures in all forms and modules.

constantname 	Name of the constant.

expression 	Expression assigned to the constant.  It can consist of literals (such as 1.0), other constants, or any of the arithmetic or logical operators except exponentiation (^).  You also can use a single string literal, such as "Error on input".  You cannot use string concatenation, variables, user-defined functions, or intrinsic Visual Basic functions (such as Chr[$])  in expressions assigned to constants.

Tip	Constants can make your programs self-documenting and easier to modify.  Unlike variables, constants can't be inadvertently changed while your program is running.

You can add a type-declaration character to constantname to indicate the data type of the constant, but this character is not part of the name.  For example:

Const MAXDIM% = 250
...
Dim AccountNames$(MAXDIM)

If you don't use a type-declaration character in the name, the constant is given a data type based on the expression in the Const statement.  Strings always yield a String constant, but numeric expressions are evaluated and the constant is given the simplest type that can represent the constant.  Because a constant must be a single predefined type, it can't be a Variant.  By definition, a Variant can appear as different data types depending on context.  Constants are not affected by Deftype statements, such as DefInt.

Caution	Constants must be defined before referring to them.  Put Global constant definitions in a single module to avoid a cross-module dependency that cannot be resolved.

Constants declared in a Sub or a Function procedure are local to that procedure.  A constant declared outside a procedure (in the Declarations section of a module) is defined throughout the module in which it is declared.  Constants declared outside a procedure using the Global reserved word can be used by all procedures in all forms and modules.  You can use constants anywhere you would use an expression.

Note	You cannot use the Global keyword to declare constants in forms, because form constants are available only to procedures within the form where they are declared.

Tip	Use all uppercase letters for constant names to make them easy to recognize in your program listings.


See Also

Deftype Statements

Let Statement


Const Statement Example

The example uses Const to define the symbolic constant PI.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const PI = 3.141592654	' Define constant.

Dim Area, Circum, Msg, Radius	' Declare variables.

Msg = "Enter the radius of a circle in centimeters."

Radius = InputBox(Msg)	' Get user input.

Circum = 2 * PI * Radius	' Calculate circumference.

Area = PI * (Radius ^ 2)	' Calculate area.

Msg = "The circumference of the circle is "

Msg = Msg & Circum & " cm. Its area is "

Msg = Msg & Area & " cm."

MsgBox Msg	' Display message.

End Sub


Declare Statement

See Also	Example

Declares references to external procedures in a dynamic-link library (DLL).

Syntax 1

Declare Sub globalname Lib "libname" [Alias "aliasname" ][([argumentlist])]

Syntax 2

Declare Function globalname Lib libname [Alias aliasname ] [([argumentlist])] [As type]

Remarks

The Declare statement has these parts:

Part	Description

Sub	Indicates that the procedure doesn't return a value.

Function	Indicates that the procedure returns a value and can be used in an expression.

globalname	The name of the Sub or Function procedure called.  Procedure names follow the same rules used for naming other Visual Basic variables.  Function procedure names can include a type-declaration character indicating the data type returned by the procedure.  This name cannot appear as the name of any other procedure.

For Function procedures, the data type of the procedure determines the data type it returns.  If the function name doesn't use a type-declaration character, you can use an As clause following the argumentlist to specify the return type of the function.

Lib	Indicates that a DLL contains the procedure being declared.  The Lib clause is required for all declarations.

libname	String literal that is the name of the DLL that contains the declared procedure.

Alias	Indicates that the procedure being called has another name in the DLL.  This is useful when the external procedure name is the same as a Visual Basic reserved word. You can also use Alias when a DLL procedure has the same name as a Global variable or constant or any other procedure in the same scope.  Alias is also useful if any characters in the DLL procedure name aren't allowed in Visual Basic names.

aliasname	String literal that identifies the name of the procedure in the DLL.

argumentlist	List of variables representing arguments that are passed to the Sub or Function procedure when it is called.

As type	Declares the data type of the value returned by a Function procedure.  The argument type may be Integer, Long, Single, Double, Currency, String (variable-length only), or Variant.

The argument argumentlist has the following syntax:

[ByVal] variable [ As type] [,[ByVal] variable [ As type] ] . . .

The following list describes the parts of argumentlist.

Part	Description

ByVal	Indicates that the argument is passed by value rather than by reference.  The ByVal reserved word cannot be used with a variable of a user-defined type.  When ByVal precedes a numeric argument variable, the actual argument is converted to the numeric type indicated in the Declare statement before being passed.  When ByVal precedes a String argument variable, the address of the null-terminated string data is sent to the procedure.  When ByVal is not included, a string descriptor is sent to the called DLL procedure.

variable	A Visual Basic variable name.  If you use a type-declaration character with variable, don't use the As clause.  If there is no As clause, the default data type of variable is used.

As type	Declares the data type of variable:  Integer, Long, Single, Double, Currency, String, Variant, Any, a user-defined type, or any object type.

Use the Any data type in an As clause only to override type checking for that argument.

Use the Declare statement to declare external procedures (procedures contained in a DLL).  A Declare statement for an external procedure can appear only in the Declarations section of a form or module.  DLL procedures declared in any module are available to all procedures in all forms and modules, but DLL procedures declared in a form are only available to the procedures in the form.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that arguments should be checked to ensure that none are passed.  In the following example, First takes no arguments.  If you use arguments in a call to First, an error occurs:

Declare Sub First Lib "MyLib" ()

When an argument list appears, the number and type of arguments are checked each time the procedure is called.  In the following example, First takes one Long argument:

Declare Sub First Lib "MyLib" (X&)

Note	You can't have fixed-length strings in the parameter list of a Declare statement because only variable-length strings can be passed to procedures.  Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed.


See Also

Call Statement


Declare Statement Example

The example uses the Declare statement to declare a reference to an external function (GetProfileString) in the Windows Kernel DLL.  To try this example, paste the code into the Declarations section of a form.  Make sure that the entire Declare statement appears as a single line in the Declarations section.  Then press F5 and click the form.

Declare Function GetProfileString Lib "Kernel" (ByVal SName$, ByVal KName$,ByVal Def$, ByVal Ret$, ByVal Size%) As Integer

Sub Form_Click ()

Dim Msg	' Declare variables

Dim KName$, Ret$, SName$

SName$ = "Intl"	' WIN.INI section name.

KName$ = "sCountry"	' WIN.INI country code.

Ret$ = String$(255, 0)	' Initialize return string.

' Call Windows Kernel DLL.

Success = GetProfileString(SName$, KName$, "", Ret$, Len(Ret$))

If Success Then	' Evaluate results.

Msg = "Your country code is: " & Ret$

Else

Msg = "There is no country code in your WIN.INI file."

End If

MsgBox Msg	' Display message.

End Sub


Deftype Statement

See Also	Example

Used in the Declarations section of forms and modules to set the default data type for variables and Function procedures.

Syntax

DefInt letterrange [,letterrange] . . .

DefLng letterrange [,letterrange] . . .

DefSng letterrange [,letterrange] . . .

DefDbl letterrange [,letterrange] . . .

DefCur letterrange [,letterrange] . . .

DefStr letterrange [,letterrange] . . .

DefVar letterrange [,letterrange] . . .

Remarks

The argument letterrange has the following form:

letter1 [-letter2]

The arguments letter1 and letter2 specify the range of variables for which a default data type will be set.  Each argument represents the first letter of variable names and can be any uppercase or lowercase letter of the alphabet.  For instance, a letter range of A-D sets the default data type for all variables that begin with A, B, C, or D. The case of the letters in letterrange isn't significant.

The reserved word you use (type in Deftype) determines which of the following data types will be the default setting of variables in letterrange: Integer(DefInt), Long(DefLng), Single(DefSng), Double(DefDbl), Currency(DefCur), String(DefStr), or Variant (DefVar).  For example, in the following program fragment, Message is a string variable:

DefStr A-Q

...

Message = "Out of stack space."

A Deftype statement affects only the form or module in which it is used.  For example, a DefInt statement in one module affects only the default data type of variables declared in that module; the default data type of variables in forms and other modules is unaffected.  If not explicitly declared with a Deftype statement, the default data type for all variables and all Function procedures in forms and modules is Variant.

When a letter range is specified, it usually defines the data type for variables that begin with letters in the first 128 characters of the ANSI character set.  However, when you specify the letter range A-Z, you set the default to the specified data type for all variables, including any that begin with international characters from the extended part of the ANSI character set (128-255).

Once the range A-Z has been specified, you cannot further redefine any subranges of variables using Deftype statements.  In fact, once a range has been specified, if you include a previously defined letter in another Deftype statement, an error occurs.  However, you can explicitly assign the data type of any variable, defined or not, using a Dim statement or a type-declaration character.  For example, you can use the following code in the Declarations section of a form or module to define a variable as a Double even though the default data type is Integer:

DefInt A-Z

Dim TaxRate As Double

You can use the following statement in a procedure to explicitly assign the data type of Pi:

Pi! = 3.141593

A type-declaration character always takes precedence over a Deftype statement.  Deftype statements don't affect elements of user-defined types.


See Also

ANSI Character Set

Let Statement


Deftype Statement Example

The example uses the Deftype statements to set default data types of variables in two ranges.  Variables beginning with the letters A-K will be Integer; variables beginning with L-Z will be String.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

DefInt A-K

DefStr L-Z

Sub Form_Click ()

NL = Chr(10)	' Define newline.

IntVal = 2.3455

Msg = "Notice that none of the string variables in this demo have "

Msg = Msg & "the $ type-declaration character appended to their "

Msg = Msg & "names." & NL & NL & "The DefStr statement defines "

Msg = Msg & "the default for variables starting with letters 'L' "

Msg = Msg & "through 'Z' to be of the string data type."

MsgBox Msg

Msg = "Notice that the variable 'IntVal' has been defined as an "

Msg = Msg & "integer. Even though it is assigned a real value, it "

Msg = Msg & "behaves as an integer, i.e., IntVal = "

Msg = Msg & IntVal & " instead of 2.3455."

MsgBox Msg	' Display message.

End Sub


Dim Statement

See Also	Example

Declares variables and allocates storage space.  When used in the Declarations section of a form or module, the variables declared with Dim are available to all procedures within the form or module.  When used at the procedure level, the variables are available only in the procedure.

Syntax

Dim varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] type] ] . . .

Remarks

The Dim statement has these parts:

Part	Description

varname	Name of a variable.

subscripts	Dimensions of an array variable.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of a variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

New	Creates a new instance of a specific object type, such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control.) or any specific control type (CommandButton, TextBox, and so on).

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

Dim A(8,3)

Dim A(0 To 8, 0 To 3)

Dim A(8, 0 To 3)

Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

Dim A(-4 To 10)

Dim B(-99 To -5, -3 To 0)

The maximum number of array dimensions allowed in a Dim statement is 60.

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

Use a Dim statement in the Declarations section or in Sub or Function procedures to declare the data type of a variable.  For example, the following statement declares the variable as an Integer.

Dim NumberOfEmployees As Integer

Also use a Dim statement in the Declarations section or in Sub or Function procedures to declare the object type of a variable.  The following statement declares a variable for a new instance of a form.

Dim X As New Form1

If New is not used when declaring an object variable, no instance of the object actually exists.  The variable must be assigned to an existing object of type using the Set statement before it can be used.  Until it is assigned to an existing object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare dynamic arrays.  After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Global or Dim statement, an error occurs.

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with zeros.  The fields of user-defined type variables are initialized as if they were separate variables.

Tip	When you use the Dim statement in a procedure, it is a generally accepted programming practice to put Dim statements at the beginning of the procedure.


See Also

Global Statement

Option Base Statement

ReDim Statement

Set Statement

Static Statement

Type Statement


Dim Statement Example

The example uses the Dim statement to declare variables at module and procedure level.  Dim is also used to declare a new instance of a form.  To try this example, which also illustrates the action of the Arrange method, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box.

Const FORMCOUNT = 5

Dim F(FORMCOUNT) As New Form1

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

F(I).Caption = "Form" & I + 1	' Change caption on copies.

F(I).Show	' Load 5 copies of Form1.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

If TypeOf F(I) Is Form1 Then

F(I).WindowState = 1	' Minimize each copy.

End If

Next I

Start = Timer	' Get timer start point.

Do

Loop Until Timer >= Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size.

MDIForm1.Arrange 3	' Arrange icons.

End Select

End Sub


Erase Statement

See Also	Example

Reinitializes the elements of fixed arrays and deallocates dynamic-array storage space.

Syntax

Erase arrayname [, arrayname] . . .

Remarks

The argument arrayname is the name of the array to be erased.  It is important to know whether an array is fixed (ordinary) or dynamic because Erase behaves differently depending on the type of array.  For fixed arrays, no memory is recovered. Erase sets the elements of a fixed array as follows:

Type of array	Effect of Erase on fixed-array elements
Fixed numeric array	Sets each element to zero
Fixed string array (variable-length)	Sets each element to zero-length ("")
Fixed string array (fixed-length)	Sets each element to zero
Fixed Variant array	Sets each element to Empty
Array of user-defined types	Sets each element as if it were a separate variable
Array of objects	Sets each element to the special value Nothing
For dynamic arrays,  Erase frees the memory used by the array.  Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.


See Also

Dim Statement

ReDim Statement


Erase Statement Example

In this example, a two-dimensional array is created, filled, and erased.  When the Erase statement is executed, zeros replace the contents of each element, but no memory space is recovered.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Static Sub Form_Click ()

Dim I As Integer, J As Integer	' Declare Variables.

Dim Total As Long

Dim Matrix(50, 50) As Integer	' Create 2-D integer array.

For I = 1 To 50

For J = 1 To 50

Matrix(I, J) = J	' Put some values into array.

Next J

Next I

Erase Matrix	' Erase array.

Total = 0	' Initialize total counter.

For I = 1 To 50

For J = 1 To 50

Total = Total + Matrix(I, J)	' Sum elements after Erase

Next J	' to make sure all are set

Next I	' to zero.

Msg = "An array has been created, filled, and erased. When the "

Msg = Msg & "Erase statement was executed, zeros replaced the "

Msg = Msg & "previous contents of each element.  The total of "

Msg = Msg & "all elements is now " & Total & ", "

Msg = Msg & "demonstrating that all elements have been cleared."

MsgBox Msg	' Display message.

End Sub


Function Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Static] [Private] Function functionname [(argumentlist)] [As type]

[statementblock]

[functionname = expression]

[Exit Function]

[statementblock]

[functionname = expression]

End Function

Remarks

All executable code must be in Function or Sub procedures.  You can't define a Function procedure inside another Function or Sub procedure.

The Function statement has these parts:

Part	Description

Static	Indicates that the Function procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Function procedure, even if they are used in the procedure.

Private	Indicates that the Function procedure is accessible only to other procedures in the module in which it exists.  No other procedure in any other module has access.  The Private keyword has no effect when declaring Function procedures in a form since they are not available outside the form anyway.

Function	Marks the beginning of a Function procedure.

functionname	Name of the function.  Function procedure names follow the same rules that constrain the names of other variables and can include a type-declaration character.  Because Function names are recognized by all procedures in all modules, functionname cannot be the same as any other globally recognized name in the program.  Such names include the names of procedures (in Visual Basic or a dynamic-link library [DLL]), Global variables, and Global constants.  To avoid a name conflict, you can use the Private reserved word to make the Function procedure local to the module in which it appears, but access to it will not be available from any procedure in any other module.  Even if you use the Private reserved word, functionname still cannot be the same as any other module-level variable, constant, or procedure name in the same module.

Note that the type of the name determines the data type returned by the Function procedure.  To specify the return data type of the Function procedure, either use an As clause following argumentlist or include a type-declaration character in the Function name.  For example, to create a Function procedure that returns a string, you can include a dollar sign in the name, use an As String clause, or give it a name defined as a string name with a DefStr statement.

argumentlist	List of variables, representing arguments, that are passed to the Function procedure when it is called.  Multiple variables are separated by commas.  Unless identified with the ByVal reserved word, individual arguments are passed by reference, so changing an argument's value inside the Function procedure changes its value in the calling procedure.  If an argument passed to a function is an expression, it is treated as if it used the ByVal reserved word: no part of the expression is altered by the function.

As type	Reserved word used to declare the data type of the value returned by the Function procedure; type can be Integer, Long, Single, Double, Currency, String, or Variant.

statementblock	Any group of statements that are to be executed within the body of the Function procedure.

expression	Return value of the function.  A Function procedure returns a value by assigning that value to the function functionname.  Any number of such assignments can appear anywhere within the procedure.  If no value is assigned to functionname, the procedure returns a default value: A numeric function returns 0, a String function returns a zero-length string (""), and a Variant function returns Empty.

Exit Function	Causes an immediate exit from a Function procedure.  Program execution continues with the statement following the statement that called the Function procedure.  Any number of Exit Function statements can appear anywhere in a Function procedure.

End Function	Marks the end of a Function procedure.

The argument argumentlist has the following syntax:

[ByVal]variable[( )] [As type] [, [ByVal]variable[( )] [ As type] ] . . .

It has these parts.

Part	Description

ByVal	Indicates that the argument is passed by value rather than by reference.  The ByVal reserved word cannot be used with a variable of a user-defined type or object.

variable	Name of the variable representing the argument.  For array variables, use the parentheses but omit the number of dimensions.

As type	Declares the data type of variable.  The type may be Integer, Long, Single, Double, Currency, String (variable-length strings only), Variant, a user-defined type, or an object data type.  Use a separate As type clause for each argument.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments.  However, unlike a Sub procedure, a Function procedure can be used in an expression in the same manner as any intrinsic function, such as Sqr, Cos, or Chr.

You can call a Function procedure by using the function name, followed by the argument list in parentheses, in an expression.  If the function has no arguments, you still must include the parentheses.

Caution	Function procedures can be recursive; that is, they can call themselves to perform a given task.  However, recursion can lead to stack overflow.  The Static reserved word is usually not used with recursive Function procedures.

To return a value from a function, assign the value to the function name.  For example, in a function named BinarySearch, you might assign the value of the constant False to the name to indicate that the value was not found.

Function BinarySearch(...)

...

' Value not found. Return a value of False.

If lower > upper Then

BinarySearch = False

Exit Function

End If
...
End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not.  Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure.  Other variables used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution	A procedure can use a variable that is not explicitly declared in the procedure, but a name conflict can occur if anything you have defined in the Declarations section has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, a Global or module-level constant or variable, or an object, Visual Basic assumes that your procedure is referring to that module-level name.  Explicitly declare variables to avoid this kind of conflict.  You can use an Option Explicit statement to force explicit declaration of variables.

Caution	Visual Basic may rearrange arithmetic expressions to increase internal efficiency.  Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.


See Also

Dim Statement

Global Statement

Option Explicit Statement

Static Statement

Sub Statement


Function Statement Example

The example uses the Function statement to declare the name of a Function procedure.  Exit Function is used to exit the procedure before the End Function statement is encountered.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, SqrN	' Declare variables.

Dim N As Double

N = InputBox("Calculate the square root of what number? ")

Msg = "The square root of " & N

SqrN = SquareRoot(N)	' Call user-defined function.

Select Case SqrN

Case 0: Msg = Msg & " is zero."

Case -1: Msg = Msg & " is an imaginary number."

Case Else: Msg = Msg & " is" & SqrN

End Select

MsgBox Msg	' Display message.

End Sub

Function SquareRoot (X As Double) As Double

Select Case Sgn(X)	' Evaluate sign of argument.

Case 1	' OK if positive.

SquareRoot = Sqr(X)

Exit Function

Case 0	' Notify user if 0.

SquareRoot = 0

Case -1	' Notify user if negative.

SquareRoot = -1

End Select

End Function


Global Statement

See Also	Example

Used  in the Declarations section of a module to declare global variables and allocate storage space.  Global variables are available to all procedures in all forms and modules.

Syntax

Global varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type] ] . . .

Remarks

The Global statement has these parts:

Part	Description

varname	Name of a variable.

subscripts	Dimensions of an array.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of a variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

New	Creates a new instance of a specific object type, such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control.) or any specific control type (CommandButton, TextBox, and so on).

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

Global A(8,3)

Global A(0 To 8, 0 To 3)

Global A(8, 0 To 3)

Array subscripts can be negative. To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

Global A(-4 To 10)

Global B(-99 To -5, -3 To 0)

The maximum number of array dimensions allowed in a Global statement is 60.

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

Use the Global statement in the Declarations section of a module to declare variables that are available to all procedures in all modules.  You can also use the Global statement to declare the data type of a variable.  For example, the following statement declares the variable as an Integer:

Global NumberOfEmployees As Integer

The following statement declares a variable for a new instance of a form:

Global X As New Form1

If New is not used when declaring an object variable, no instance of the object actually exists.  The variable must be assigned to an existing object of type using the Set statement before it can be used.  Until it is assigned to an existing object, the declared object varaible has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Global statement with empty parentheses to declare dynamic arrays.  After declaring a dynamic array, use the ReDim statement within a procedure level to define the number of dimensions and elements in the array.  If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Global or Dim statement, an error occurs.

Note	You cannot use the Global statement in forms, because form variables are available only to procedures within the form where they are declared.

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with zeros.  The fields of user-defined type variables are initialized as if they were separate variables.


See Also

Const Statement

Dim Statement

Option Base Statement

ReDim Statement

Static Statement

Type Statement


Global Statement Example

The example uses the Global statement to declare two variables in a module.  The first is a global dynamic-array variable; the second is a global integer variable.  To try this example, paste the Form_Click procedure into the Declarations section of a form containing a list box named List1. Paste the remaining code into the Declarations section of a module.  Then press F5 and click the form.

Sub Form_Click ()

LoadGlobalArray	' Call GlobalDemo procedure.

For I = 1 To UBound(TestArray)	' Determine array size and

List1.AddItem TestArray(I)	' put array items in list box.

Next I

End Sub

Global TestArray()	' Declare dynamic-array.

Global Size As Integer	' Declare integer.

Sub LoadGlobalArray ()

Dim I	' Declare local variables.

Size = Int(100 * Rnd + 1)	' Generate random size.

ReDim TestArray(Size)	' Define how many elements.

For I = 1 to Size	' Index of elements.

TestArray(I) = Int(100 * Rnd + 1)	' Put random number in each element.

Next I

End Sub


LBound Function

See Also	Example

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

Syntax

LBound(array [,dimension])

Remarks

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

The LBound function has the following parts:

Part	Description

array	Name of an array variable.

dimension	Integer indicating which dimension's lower bound is returned.  Use 1 for the first dimension, 2 for the second dimension, and so on.  If dimension is omitted, 1 is assumed.

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

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

Statement	Return Value

LBound(A, 1)	1

LBound(A, 2)	0

LBound(A, 3)	-3

The default lower bound for any dimension is either 0 or 1, depending on the setting of the Option Base statement.

Arrays for which dimensions are set using the To clause in a Dim, Global, ReDim, or Static statement can have any integer value as a lower bound.


See Also

Dim Statement

Global Statement

Option Base Statement

ReDim Statement

Static Statement

UBound Function


LBound Function Example

The example uses the LBound function to determine the lower bound for a two-dimensional array.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg, NL, TB	' Declare variables.

Dim Array()	' Declare array variable.

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

' Generate some random dimensions between 2 and 10 for array size.

A = -Int(9 * Rnd + 2)	' First dimension.

B = Int(9 * Rnd + 2)	' Second dimension.

C = Int(9 * Rnd + 2)	' Third dimension.

ReDim Array(A To 20, B to 20 , C to 20)	' Set dimensions.

Msg = "The test array has the following lower bounds: " & NL

Msg = Msg & TB & "Dimension 1 = " & LBound(Array, 1) & NL

Msg = Msg & TB & "Dimension 2 = " & LBound(Array, 2) & NL

Msg = Msg & TB & "Dimension 3 = " & LBound(Array, 3)

MsgBox Msg	' Display message.

End Sub


Let Statement

See Also	Example

Assigns the value of an expression to a variable.

Syntax

[Let] variable = valueexpression

Remarks

The Let statement has these parts:

Part	Description

variable	Name of the variable

=	Assignment operator

valueexpression	Value assigned to the variable

The reserved word Let is always optional.  You can assign a String or numeric expression to a variable without using the Let reserved word.  In fact, most Basic programmers never use the Let reserved word.

A value expression can be assigned to a variable only if the data types they have are compatible.  You can't assign String expressions to numeric variables, and you can't assign numeric expressions to String variables.  If you do, a Type mismatch error occurs at compile time.

Variant variables can be assigned either String or numeric expressions.  However, the reverse is not true.  Any Variant except a Null can be assigned to a String variable, but only a Variant that contains a value that can be interpreted as a number can be assigned to a numeric variable.  Use the IsNumeric function to determine if the Variant can be converted to a number.

Caution	Assigning an expression of one numeric data type to a variable of a different numeric data type coerces the value of the expression into the data type of the resulting variable.

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type.  Use the LSet statement to assign record variables of different user-defined types.


See Also

Const Statement

IsNumeric Function

LSet Statement

Set Statement


Let Statement Example

The example uses statements with and without the Let reserved word to assign the value of an expression to a variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Pi	' Declare variable.

' Assign Pi using Let statement.

Let Pi = 4 * Atn(1)

' Assign Msg without Let statement.

Msg = "The area of circle whose radius is 3 inches is "

Msg = Msg & (Pi * (3^2)) & " inches."

MsgBox Msg	' Display message.

End Sub


Option Base Statement

See Also	Example

Declares the default lower bound for array subscripts.

Syntax

Option Base number

Remarks

The Option Base statement is never required.  However, if used, it can appear only once in a form or module and can occur only in the Declarations section.  If you choose to use an Option Base statement, it must be used before you declare the dimensions of any arrays.

The value of number must be either 0 or 1.  The default base is 0.

The Option Base statement has no effect on arrays within user-defined types.  The lower bound for all such arrays is always 0.

Tip	The To clause in the Dim, Global, ReDim, and Static statements provides a more flexible way to control the range of an array's subscripts.  However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.


See Also

Dim Statement

Global Statement

LBound Function

ReDim Statement

Static Statement


Option Base Statement Example

The example uses the Option Base statement to override the default base array subscript value of 0.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Option Base 1	' Module level statement.

Sub Form_Click ()

Dim A(), Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

ReDim A(20)	' Create an array.

Msg = "The lower bound of the A array is " & LBound(A) & "."

Msg = Msg & NL & "The upper bound is " & UBound(A) & "."

MsgBox Msg	' Display message.

End Sub


Option Compare Statement

See Also	Example

Declares the default comparison mode to use when string data is compared.

Syntax

Option Compare {Binary | Text}

Remarks

The Option Compare statement is used in the Declarations section of a form or module to specify the string comparison method for that form or module.

String comparisons can be either Binary or Text.

Binary comparisons are case sensitive; so, for example, an "M" doesn't match an "m".  When determining whether a character is less than, equal to, or greater than another character, the program uses the character's relative order of appearance in the ANSI character set.

Text comparisons are case insensitive; so, for example, an "M" matches an "m".  In addition, the relative order of characters is not the same as it is for Binary.  For Text comparisons, the relative order of characters is determined by the setting of the country code in the international section of your WIN.INI file.

When  a form or module doesn't include an Option Compare statement, the default text comparison method is Binary.


See Also

ANSI Character Set

Comparison Operators

InStr Function

StrComp Function


Option Compare Statement Example

The example uses the Option Compare statement to set the string comparison method.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Option Compare Text	' Set string comparison.

Sub Form_Click ()

Dim LName, Msg, NameStr, UName	' Declare variables.

NameStr = InputBox("Enter your name.")	' Get name from user.

UName = UCase(NameStr)	' Make uppercase version.

LName = LCase(NameStr)	' Make lowercase  version.

If UName Like LName Then	' Compare them.

Msg = "'" & UName & "' matches '" & LName & "'. End the program, "

Msg = Msg & "then remove the 'Option Compare Text' line from the "

Msg = Msg & "Declarations section of the form and try the example again."

Else

Msg = "Now, '" & UName & "' does not match '" & LName & "'."

End If

MsgBox Msg	' Display message.

End Sub


Option Explicit Statement

See Also	Example

Forces explicit declaration of all variables.

Syntax

Option Explicit

Remarks

The Option Explicit statement is used in the Declarations section of a form or module to force explicit declaration of all variables for that form or module.

If you don't use the Option Explicit statement, all undeclared variables are of Variant data type (unless the default type is otherwise specified with a Deftype statement).  When you use the Option Explicit statement, all variables must be explicitly declared before they are used in Dim, Global, ReDim, or Static statements .  If you attempt to use an undeclared variable name, a Variable not declared error occurs at compile time.

Tip	Use Option Explicit to avoid mistyping the name of an existing variable or to avoid risking confusion in code in which the scope of the variable is not clear.

Note	You can automatically include an Option Explicit statement in your code by selecting the Environment menu item from the Options menu and changing the Require Variable Declaration option to Yes.


See Also

Const Statement

Deftype Statements

Dim Statement

Function Statement

Global Statement

ReDim Statement

Static Statement

Sub Statement


Option Explicit Statement Example

The example uses Option Explicit to force you to explicitly declare all variables. To try this example, paste the code into the Declarations section of a form.  Then press F5.  You'll immediately notice that because the variable X has not been formally declared using the Dim statement or equivalent, that the Variable not defined error message is displayed.

Option Explicit	' Force variable declaration.

Sub Form_Click ()

Print X	' Print X on form

End Sub


ReDim Statement

See Also	Example

Used at the procedure level to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [As type][, varname(subscripts) [As type] ] . . .

Remarks

The ReDim statement has these parts:

Part	Description

Preserve	Preserves the data in an existing array when you resize the last dimension.

varname	Name of a variable.

subscripts	Dimensions of an array.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of a variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper]. . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

ReDim A(8,3)

ReDim A(0 To 8, 0 To 3)

ReDim A(8, 0 To 3)

Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

ReDim A(-4 To 10)

ReDim B(-99 To -5, -3 To 0)

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

The ReDim statement is usually used to size or resize a dynamic array that has already been formally declared using a Global or Dim statement with empty parentheses (without dimension subscripts).  If you first declare a dynamic array using a Global or Dim statement and include no dimension subscripts, the maximum number of array dimensions you can later specify with ReDim is eight.  If your array requires more than eight dimensions, you can use the ReDim statement  within a procedure to initially declare a local dynamic-array variable.  Your array can then have as many as 60 dimensions.

You can use the ReDim statement repeatedly to change the number of elements in an array.  However, you can't use ReDim to change the number of dimensions in an array.  For example, if you declare an array consisting of two dimensions (for example, ReDim A(10,10)), you can't use ReDim later to change it to an array with three dimensions. (for example, ReDim A(12,12,12,) ).  Similarly, you can't declare an array of Integers and later use ReDim to change the array to another data type.

If you use the Preserve reserved word, you can resize only the last array dimension.  For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you cannot resize the first one. You can only change the size of the last dimension and still preserve the contents of the array.  The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)

...

ReDim Preserve X(10, 10, 15)

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with ANSI zeros (Chr(0)).  The fields of user-defined type variables are initialized as if they were separate variables.


See Also

Dim Statement

Global Statement

Option Base Statement

Static Statement


ReDim Statement Example

The example uses the ReDim statement to dynamically resize an array while a procedure is running.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestArray() As Integer	' Declare dynamic array.

Dim I, Msg, Size	' Declare variables.

Size = Int(100 * Rnd + 1)	' Generate random number.

ReDim TestArray(Size)	' Make array have Size elements.

For I = 1 To Size	' Index for number of elements.

TestArray(I) = Rnd	' Put number in each element.

Next I

ReDim TestArray(Size * 10)	' Make array 10 times larger.

For I = 1 To Size * 10	' Index for number of elements.

TestArray(I) = Rnd	' Put number in each element.

Next I

Msg = "This demo created a dynamic array of " & Size

Msg = Msg & " elements and filled each with a random number.  "

Msg = Msg & "It then resized the array to " & (Size * 10)

Msg = Msg & " elements, again filling each with a random number.  "

Msg = Msg & "Finally, it restored the array back to "

Msg = Msg & Size & " elements."

MsgBox Msg	' Display message.

End Sub


Rem Statement

Example

Used to include explanatory remarks in a program.

Syntax1

Rem remark

Syntax 2

' remark

Remarks

The argument remark is the text of any comments you want to include in your program.  Spaces and punctuation are permitted.  Comment text appears exactly as entered when the program is listed.  You can use comments to document how your code works or to provide any other information with your code.

If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement.  Execution continues with the first executable statement following the Rem statement.

As shown in syntax 2, you can use a single quotation mark (apostrophe) instead of the Rem reserved word.  If the Rem reserved word follows other statements on a line, it must be separated from the statements by a colon.  However, when you use a single quotation mark, the colon is not required after other statements.


Rem Statement Example

The example illustrates the various forms of the Rem statement syntax.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg1, Msg2	' Declare variables.

Rem This is the first form of the syntax.

' This is the second form of the syntax.

Msg1 = "Hello" : Rem Comment after a statement separated by a colon.

Msg2 = "Goodbye" ' Second form after a statement without a colon.

MsgBox "This example illustrates Rem statement syntax."

End Sub


Set Statement

See Also	Example

Assigns an object reference to a variable.

Syntax

Set objectvar = {objectexpr | New formtype | Nothing}

Remarks

The Set statement has the following parts:

Part	Description

objectvar	Name of the variable to which the object reference is being assigned.

objectexpr	Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object.

New	Reserved word used to create a new instance of a specific object type (created as design time), such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control.) or any specific control type (CommandButton, TextBox, and so on).

formtype	A specific form type, for example Form1.

Nothing	Reserved word used to discontinue association of objectvar with any specific object.  Assigning objectvar to Nothing releases all the resources associated with the previously referenced object when no other variable refers to it.

To be valid, objectvar must be an object type consistent with the object being assigned to it.  And, it must either have been explicitly declared (using a Dim, Global, ReDim, or Static statement) or implicitly declared for you by Visual Basic, as occurs, for example, with form types.

The following example illustrates how Dim is used to formally declare the variable LedgerForm as Form1.  The Dim statement only declares a variable of type Form1.  No instance of Form1 actually exists.  Set then assigns a reference to a new instance of Form1 to the LedgerForm variable.

Dim LedgerForm As Form1

Set LedgerForm = New Form1

In the following example for a control, the variable X is declared (using Dim) as a variable that refers to a list box.  The Set statement assigns the object reference for X to an actual instance of a list box on Form1, in this case List1.

Dim X As ListBox

Set X = Form1!List1

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable.  Instead, a reference to the object is created.  More than one object variable can refer to the same object.  Because these variables are references to, rather than copies of the object, any change in the object is reflected in all variables that refer to it.

However, when you use the New reserved word in the Set statement, you are actually creating a new instance of the referenced form type.  The new instance is not loaded until you either explicitly load it using the Load statement or implicitly load it by referring to one of its properties, methods, or members in code.


See Also

Dim Statement

Global Statement

ReDim Statement

Static Statement


Set Statement Example

The example uses the Set statement to declare a reference to a new instance of Form1.  To try this example, which also illustrates the action of the Arrange method, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box..

Const FORMCOUNT = 5

Dim F(1 To FORMCOUNT) As Form1	' Create object type variable.

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

Set F(I) = New Form1	' Refer to new instance of Form1.

F(I).Caption = "Form" & I + 1	' Change caption on copies.

F(I).Show	' Load 5 copies of Form1.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

If TypeOf F(I) Is Form1 Then

F(I).WindowState = 1	' Minimize each copy.

End If

Next I

Start = Timer	' Get timer start point.

Do

Loop Until Timer >= Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size.

MDIForm1.Arrange 3	' Arrange icons.

End Select

End Sub


Static Statement

See Also	Example

Used at the procedure level to declare  variables and allocate storage space.  Variables declared with the Static statement retain their value as long as the program is running.

Syntax

Static varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type] ] . . .

Remarks

The Static statement has these parts:

Part	Description

varname	Name of a variable.

subscripts	Dimensions of an array.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of the variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

New	Creates a new instance of a specific object type, such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control) or any specific control type (CommandButton, TextBox, and so on).

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

Static A(8,3)

Static A(0 To 8, 0 To 3)

Static A(8, 0 To 3)

Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

Static A(-4 To 10)

Static B(-99 To -5, -3 To 0)

The maximum number of array dimensions allowed in a Static statement is 60.

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

Use the Static statement in nonstatic procedures to explicitly declare Static variables.  You must use Static to declare a fixed-size array in nonstatic procedures.  In Static procedures, you can use either Static or Dim to declare Static variables.

Use a Static statement within a procedure to declare the data type of a Static variable.  For example, the following statement declares a fixed-size array of integers:

Static EmployeeNumber(200) As Integer

Also use the Static statement in Sub or Function procedures to declare the object type of a variable.  The following statement declares a variable for a new instance of a form:

Static X As New Form1

If New is not used when declaring an object variable, no instance of the object actually exists.  The variable must be assigned to an existing object of type using the Set statement before it can be used.  Until it is assigned to an existing object, the declared object varaible has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Note	The Static statement and the Static reserved word affect the lifetime of variables differently.  If you declare a procedure using the Static reserved word (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once and the value of the variables is preserved for the entire time the program is running.  For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited.  The Static statement is used to declare variables within nonstatic procedures to preserve their value as long as the program is running.

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with zeros.  The fields of user-defined type variables are initialized as if they were separate variables.

Tip	When you use the Static statement in a procedure, it is a generally accepted programming practice to put Static statements at the beginning of the procedure with any Dim statements.


See Also

Dim Statement

Function Statement

Global Statement

Option Base Statement

ReDim Statement

Sub Statement


Static Statement Example

The example uses the Static statement to declare a persistent variable in the Picture_Click procedure.  To try this example, which also illustrates the action of the Arrange method, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box..

Const FORMCOUNT = 5

Dim F(1 To FORMCOUNT) As New Form1

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

F(I).Caption = "Form" & I + 1	' Change caption on copies.

F(I).Show	' Load 5 copies of Form1.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount As Integer	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

If TypeOf F(I) Is Form1 Then

F(I).WindowState = 1	' Minimize each copy.

End If

Next I

Start = Timer	' Get timer start point.

Do

Loop Until Timer >= Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size

MDIForm1.Arrange 3	' Arrange icons

End Select

End Sub


Sub Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Static] [Private] Sub subname [(argumentlist)]

[statementblock]

[Exit Sub]

[statementblock]

End Sub

Remarks

All executable code must be in Sub or Function procedures.  You can't define a Sub procedure inside another Sub or Function procedure.

The Sub statement has these parts:

Part	Description

Static	Indicates that the Sub procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Sub procedure, even if they are used in the procedure.

Private	Indicates that the Sub procedure is accessible only to other procedures in the module in which it exists.  No other procedure in any other module has access to it.  The Private keyword has no effect when declaring Sub procedures in a form since they are not available outside the form anyway.

Sub	Marks the beginning of a Sub procedure.

subname	Name of the procedure.  Sub procedure names follow the same rules that constrain the names of other variables but cannot include a type-declaration character.  Because Sub names are recognized by all procedures in all modules, subname cannot be the same as any other globally recognized name in the program.  Such names include the names of procedures (in Visual Basic or declared dynamic-link library [DLL]) procedures, Global variables, and Global constants.  To avoid a name conflict, you can use the Private reserved word to make the Sub local to the module in which it appears, but access to it will not be available from any procedure in any other module.  Even if you use the Private reserved word, subname cannot be the same as any other module-level variable, constant, or procedure name in the same module.

argumentlist	List of variables, representing arguments, that are passed to the Sub procedure when it is called.  Multiple variables are separated by commas.  Unless identified with the ByVal reserved word, arguments are passed by reference, so changing an argument's value inside the Sub procedure changes its value in the calling procedure.

statementblock	Any group of statements that are executed within the body of the Sub procedure.

Exit Sub	Causes an immediate exit from a Sub procedure.  Program execution continues with the statement following the statement that called the Sub procedure.  Any number of Exit Sub statements can appear anywhere in a Sub procedure.

End Sub	Marks the end of a Sub procedure.

The argument argumentlist has this syntax:

[ByVal] variable[( )] [As type] [, [ByVal]variable[( )] [ As type] ] . . .

It has these parts:

Part	Description

ByVal	Indicates the argument is passed by value rather than by reference.  The ByVal reserved word cannot be used with a variable of a user-defined type or object.

variable	Name of the variable to pass as an argument.  For array variables, use the parentheses but omit the number of dimensions.

As type	Declares the data type of variable.  The type may be Integer, Long, Single, Double, Currency, String (variable-length strings only), Variant, a user-defined type, or an object data type.  Use a separate As type clause for each argument.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments.  However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You can call a Sub procedure using the procedure name followed by the argument list.  See the Call statement for specific information on how to call Sub procedures.

Caution	Sub procedures can be recursive; that is, they can call themselves to perform a given task.  However, recursion can lead to stack overflow. The Static reserved word usually is not used with recursive Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not.  Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure.  Other variables used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution	A procedure can use a variable that is not explicitly declared in the procedure, but a name conflict can occur if anything you have defined in the Declarations section has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, a Global or module-level constant or variable, or an object, Visual Basic assumes that your procedure is referring to that module-level name.  Explicitly declare variables to avoid this kind of conflict.  You can use an Option Explicit statement to force explicit declaration of variables.

Note   You can't use GoSub, GoTo, or Return to enter or exit a Sub procedure.


See Also

Call Statement

Dim Statement

Function Statement

Global Statement

Option Explicit Statement

Static Statement


Sub Statement Example

The example uses the Sub statement to declare the name of two Sub procedures.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B	' Declare local variables.

A = InputBox("What is the length?")	' Ask for length of rectangle.

B = InputBox("What is the width?")	' Ask for width of rectangle.

SubDemo A, B	' Call Sub with arguments.

End Sub

Sub SubDemo(RLen, RWid)	' Sub with two arguments.

Dim Area	' Declare local variable.

Area = RLen * RWid	' Calculate area of rectangle.

MsgBox "Total area is " & Area	' Display result.

End Sub


Type Statement

Example

Defines a user-defined data type containing one or more elements.

Syntax

Type usertype
  elementname [(subscripts)] As typename
[ elementname [(subscripts)] As typename]
. . .
End Type

Remarks

The Type statement has these parts:

Part	Description

Type	Marks the beginning of a user-defined type.

usertype	Name of a user-defined data type.  It follows standard variable naming conventions.

elementname	Name of an element of the user-defined data type.  It follows standard variable-naming conventions.

subscripts	Dimensions of an array element.  You can declare multiple dimensions.  The syntax of subscripts is described below.

typename	One of these data types: Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant,  or another user-defined type.  The argument typename can't be an object type.

End Type	Marks the end of a user-defined type.

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  The maximum number of array dimension is 60.

The Type statement can be used only in the Declarations section of a module.  Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere in your application.  Use Dim, Global, ReDim, or Static to declare a variable of a user-defined type.

Line numbers and line labels aren't allowed in Type...End Type blocks.

User-defined types are often used with data records because data records frequently consist of a number of related elements of different data types.

The following example shows the use of static arrays in a user-defined type:

Type StateData

CityCode (1 To 100) As Integer ' Declare a static array.

County As String * 30

End Type

Dim Washington(1 To 100) As StateData

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData.

When you declare a static array within a user-defined type, its dimensions must be declared with numeric constants rather than variables.


Type Statement Example

The example uses Type to create a user-defined type with three elements. A variable is then declared of the user-defined type, and data is assigned to each element.  To try this example, paste the user-defined type definition into the Declarations section of a module.  Paste the remaining code into the Declarations section of a form.  Then press F5 and click the form.

Type TestRecord	' Create user-defined type.

CustNum As Long

CustName As String * 38

CustPurchase As String * 24

End Type

Sub Form_Click ()

Dim Answer, FileNum, Index, Msg, NL, TB	' Declare variables.

Static CustEntry As TestRecord	' Create output buffer.

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

FileNum = FreeFile	' Get file number.

Open "TESTFILE" For Random As FileNum

Index = 1	' Keep track of records.

Do	' Get data to fill all

CustEntry.CustNum = Index	' the elements of the

Msg = "Enter customer name:"	' data records.

CustEntry.CustName = InputBox(Msg)

If CustEntry.CustName = String(38, 32) Then Exit Do

Msg = "Enter purchase:"

CustEntry.CustPurchase = InputBox(Msg)

Msg = "Customer #"

Msg = Msg & CustEntry.CustNum & NL

Msg = Msg & CustEntry.CustName & NL

Msg = Msg & CustEntry.CustPurchase & NL

Msg = Msg & NL & "Is this information correct?"

Answer = MsgBox(Msg, 4)	' Show record, confirm.

If Answer = 6 Then	' If Yes

Put FileNum, Index, CustEntry

Index = Index + 1	' Increment record.

End If

Loop

Close FileNum	' Close file.

Msg = "The records you input have been written to a file.  "

Msg = Msg & "Choose OK to remove the test file from your disk."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove test file.

End Sub


UBound Function

See Also	Example

Returns the largest available subscript for the indicated dimension of an array.

Syntax

UBound(array [, dimension])

Remarks

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

The UBound function has these parts:

Part	Description

array	Name of an array variable.

dimension	Integer indicating which dimension's upper bound is returned.  Use 1 for the first dimension, 2 for the second dimension, and so on.  If dimension is omitted, 1 is assumed.

UBound returns the values listed in the table below for an array with these dimensions:

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

Statement	Return Value

UBound(A, 1)	100

UBound(A, 2)	3

UBound(A, 3)	4


See Also

Dim Statement

Global Statement

LBound Function

Option Base Statement

ReDim Statement

Static Statement


UBound Function Example

The example uses the UBound function to determine the upper bound for a two-dimensional array.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg, NL, TB	' Declare variables.

Dim Array()	' Declare array variable.

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

' Generate some random dimensions between 2 and 10 for array size.

A = -Int(9 * Rnd + 2)	' First dimension.

B = Int(9 * Rnd + 2)	' Second dimension.

C = Int(9 * Rnd + 2)	' Third dimension.

ReDim Array(A To 20, B to 20 , C to 20)	' Set dimensions.

Msg = "The test array has the following lower bounds: " & NL

Msg = Msg & TB & "Dimension 1 = " & UBound(Array, 1) & NL

Msg = Msg & TB & "Dimension 2 = " & UBound(Array, 2) & NL

Msg = Msg & TB & "Dimension 3 = " & UBound(Array, 3)

MsgBox Msg	' Display message.

End Sub


Math Functions

Abs Function

Atn Function

Cos Function

Exp Function

Fix Function

Int Function

Log Function

Rnd Function

Sgn Function

Sin Function

Sqr Function

Tan Function

Derived Math Functions


Abs Function

See Also	Example

Returns the absolute value of a number.

Syntax

Abs(number)

Remarks

The argument number can be any valid numeric expression.  The absolute value of a number is its unsigned magnitude.  For example, ABS(-1) and ABS(1) both return 1.

The data type of the return value is the same as that of the number argument.  However, if number is a Variant of VarType 8 (String) and can be converted to a number, the return value will be a Variant of VarType 5 (Double).  If the numeric expression results in a Null, Abs returns a Null.


See Also

Math Functions


Abs Function Example

The example finds the approximate value for a cube root.  It uses Abs to determine the absolute difference between two numbers.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Precision, Value, X, X1, X2	' Declare variables.

Precision = .00000000000001

Value = InputBox("Enter a value: ")	' Prompt for input.

X1 = 0: X2 = Value	' Make first two guesses.

' Loop until difference between guesses is less than precision.

Do Until Abs(X1 - X2) < Precision

X = (X1 + X2) / 2

If X * X * X - Value < 0 Then	' Adjust guesses.

X1 = X

Else

X2 = X

End If

Loop

Msg = "The cube root of " & Value & " is "

Msg = Msg & X & "."

MsgBox Msg	' Display message.

End Sub


Atn Function

See Also	Example

Returns the arctangent of a number.

Syntax

Atn(number)

Remarks

The argument number can be any valid numeric expression.

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

The result is expressed in radians and is in the range -Pi/2 to Pi/2 radians.  Pi is approximately 3.141593.

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

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


See Also

Cos Function

Sin Function

Tan Function

Math Functions

Derived Math Functions


Atn Function Example

The example uses Atn to calculate Pi.  By definition, Atn(1) is 45 degrees; 180 degrees equals Pi radians.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Pi	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Msg = "Pi is equal to " & Pi

MsgBox Msg	' Display results.

End Sub


Cos Function

See Also	Example

Returns the cosine of an angle.

Syntax

Cos(angle)

Remarks

The argument angle can be any valid numeric expression measured in radians.

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

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by Pi/180.  To convert radians to degrees, multiply radians by 180/Pi.  Pi is approximately 3.141593.


See Also

Atn Function

Sin Function

Tan Function

Math Functions

Derived Math Functions


Cos Function Example

The example uses Cos to calculate the cosine of an angle with a user-specified number of degrees.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degrees, Msg, Pi, Radians	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Degrees = InputBox("Enter an angle in degrees.")	' Get user input.

Radians = Degrees * (Pi / 180)	' Convert to radians.

Msg = "The cosine of a " & Degrees

Msg = Msg & " degree angle is "

Msg = Msg & Cos(Radians) & "."

MsgBox Msg	' Display results.

End Sub


Exp Function

See Also	Example

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

Syntax

Exp(number)

Remarks

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

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


See Also

Log Function

Math Functions

Derived Math Functions


Exp Function Example

The example uses Exp to calculate the value of e.  Exp(1) is e raised to the power of 1.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

' Exp(x) is e ^x so Exp(1) is e ^1 or e.

Dim Msg, ValueOfE	' Declare variables.

ValueOfE = Exp(1)	' Calculate value of e.

Msg = "The value of e is " & ValueOfE

MsgBox Msg	' Display message.

End Sub


Int Function, Fix Function

See Also	Example

Return the integer portion of a number.

Syntax

Int(number)

Fix(number)

Remarks

The argument number can be any valid numeric expression.  Both Int and Fix remove the fractional part of number and return the resulting integer value.

The data type of the return value is the same as that of the number argument.  However, if number is a Variant of VarType 8 (String) that can be converted to a number or a Variant of VarType 7 (Date), the return type will be a Variant of VarType 5 (Double).  If the numeric expression results in a Null, Int and Fix return a Null.

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

Fix(number) is equivalent to:

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


See Also

Data Type Conversion Functions

Math Functions


Int Function, Fix Function Example

The example illustrates the difference between Int and Fix.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, TB	' Declare variables.

NL = Chr(13) & Chr(10): TB = Chr(9)	' Define newline, tab.

Msg = "Int(-99.8) returns" & TB & Int(-99.8)

Msg = Msg & TB & "Fix(-99.8) returns" & TB & Fix(-99.8)

Msg = Msg & NL & "Int(-99.2) returns" & TB & Int(-99.2)

Msg = Msg & TB & "Fix(-99.2) returns" & TB & Fix(-99.2)

MsgBox Msg	' Display message.

End Sub


Log Function

See Also	Example

Returns the natural logarithm of a number.

Syntax

Log(number)

Remarks

The argument number can be any valid numeric expression that results in a value greater than 0.  The natural logarithm is the logarithm to the base e.  The constant e is approximately 2.718282.

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

Logn = Log(x) / Log(n)

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

Static Function Log10(X)

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

End Function


See Also

Exp Function

Math Functions

Derived Math Functions


Log Function Example

The example calculates the value of e, then uses the Log function to calculate the natural logarithm of e to the first, second, and third powers.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL	' Declare variables.

NL = Chr(13) & Chr(10)	' Define newline.

Msg = Exp(1) & NL

For I = 1 To 3	' Do three times.

Msg = Msg & Log(Exp(1) ^ I) & NL

Next I

MsgBox Msg	' Display message.

End Sub


Randomize Statement

See Also	Example

Initializes the random-number generator.

Syntax

Randomize [number]

Remarks

The argument number can be any valid numeric expression.  Number is used to initialize the random-number generator by giving it a new seed value.  If you omit number, the value returned by the Timer function is used as the new seed value.

If Randomize is not used, the Rnd function returns the same sequence of random numbers every time the program is run.  To have the sequence of random numbers change each time the program is run, place a Randomize statement with no argument at the beginning of the program.


See Also

Rnd Function

Timer Function


Randomize Statement Example

The example simulates rolling a pair of dice by generating random values from 1 to 6.  Each time this program is run, Randomize uses the Timer function to generate a new random-number sequence.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg	' Declare variables.

Randomize	' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)	' Generate first die value.

Dice2 = Int(6 * Rnd + 1)	' Generate second die value.

Msg = "You rolled a " & Dice1

Msg = Msg & " and a " & Dice2

Msg = Msg & " for a total of "

Msg = Msg & (Dice1 + Dice2) & "."

MsgBox Msg	' Display message.

End Sub


Rnd Function

See Also	Example

Returns a random number.

Syntax

Rnd[(number)]

Remarks

The argument number can be any valid numeric expression.

The Rnd function returns a Single value less than 1 but greater than or equal to 0.

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

Value of number	Number returned

< 0	The same number every time, as determined by number.

> 0	The next random number in the sequence.

= 0	The number most recently generated.

number omitted	The next random number in the sequence.

The same random-number sequence is generated every time the program is run because each successive call to the Rnd function uses the previous random number as a seed for the next number in the random-number sequence.

To have the program generate a different random-number sequence each time it is run, use the Randomize statement without an argument to initialize the random-number generator before Rnd is called.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.


See Also

Randomize Statement

Math Functions


Rnd Function Example

The example uses the Rnd function to simulate rolling a pair of dice by generating random values from 1 to 6.  Each time this program is run, Randomize uses the Timer function to generate a new random-number sequence.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg	' Declare variables.

Randomize	' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)	' Generate first die value.

Dice2 = Int(6 * Rnd + 1)	' Generate second die value.

Msg = "You rolled a " & Dice1

Msg = Msg & " and a " & Dice2

Msg = Msg & " for a total of "

Msg = Msg & (Dice1 + Dice2) & "."

MsgBox Msg	' Display message.

End Sub


Sgn Function

See Also	Example

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

Remarks

The argument number can be any valid numeric expression.  Its sign determines the value returned by the Sgn function:

If number > 0, then Sgn(number) returns 1.

If number = 0, then Sgn(number) returns 0.

If number < 0, then Sgn(number) returns -1.


See Also

Math Functions


Sgn Function Example

The example uses Sgn to determine the sign of a number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Number	' Declare variables.

Number = InputBox("Enter a number.")	' Get user input.

Select Case Sgn(Number)	' Evaluate user input.

Case 0	' Zero.

Msg = "You entered zero."

Case 1	' Positive.

Msg = "You entered a positive number."

Case -1	' Negative.

Msg = "You entered a negative number."

End Select

MsgBox Msg	' Display results.

End Sub


Sin Function

See Also	Example

Returns the sine of an angle.

Syntax

Sin(angle)

Remarks

The argument angle can be any valid numeric expression measured in radians.

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

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by Pi/180.  To convert radians to degrees, multiply radians by 180/Pi.  Pi is approximately 3.141593.


See Also

Atn Function

Cos Function

Tan Function

Math Functions

Derived Math Functions


Sin Function Example

The example uses Sin to calculate the sine of an angle with a user-specified number of degrees.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degrees, Msg, Pi, Radians	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Degrees = InputBox("Enter an angle in degrees.")	' Get user input.

Radians = Degrees * (Pi / 180)	' Convert to radians.

Msg = "The sine of a " & Degrees

Msg = Msg & " degree angle is "

Msg = Msg & Sin(Radians) & "."

MsgBox Msg	' Display results.

End Sub


Sqr Function

See Also	Example

Returns the square root of a number.

Syntax

Sqr(number)

Remarks

The argument number can be any valid numeric expression that results in a value greater than or equal to 0.

The return type of Sqr function is Double.


See Also

Math Functions


Sqr Function Example

The example uses Sqr to calculate the square root of a user-supplied number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Number	' Declare variables.

Msg = "Enter a non-negative number."

Number = InputBox(Msg)	' Get user input.

If Number < 0 Then

Msg = "Cannot determine the square root of a negative number."

Else

Msg = "The square root of " & Number & " is "

Msg = Msg & Sqr(Number) & "."

End If

MsgBox Msg	' Display results.

End Sub


Tan Function

See Also	Example

Returns the tangent of an angle.

Syntax

Tan(angle)

Remarks

The argument angle can be any valid numeric expression measured in radians.

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

Tan returns a Double.  If the return value is too large, an Overflow error occurs.

To convert degrees to radians, multiply degrees by Pi/180.  To convert radians to degrees, multiply radians by 180/Pi.  Pi is approximately 3.141593.


See Also

Atn Function

Cos Function

Sin Function

Math Functions

Derived Math Functions


Tan Function Example

The example uses Tan to calculate the tangent of an angle with a user-specified number of degrees.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degrees, Msg, Pi, Radians	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Degrees = InputBox("Enter an angle in degrees.")	' Get user input.

Radians = Degrees * (Pi / 180)	' Convert to radians.

Msg = "The tangent of a " & Degrees

Msg = Msg & " degree angle is "

Msg = Msg & Tan(Radians) & "."

MsgBox Msg	' Display results.

End Sub


Derived Math Functions

The following is a list of nonintrinsic mathematical functions that can be derived from the intrinsic math functions provided with Visual Basic:

Function	Visual Basic equivalent

Secant	Sec(X) = 1 / Cos(X)

Cosecant	Cosec(X) = 1 / Sin(X)

Cotangent	Cotan((X) = 1 / Tan(X)

Inverse Sine	Arcsin(X) = Atn(X / Sqr(-X * X + 1))

Inverse Cosine	Arccos(X) = Atn(X / Sqr(-X * X + 1)) + 1.5708

Inverse Secant	Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn(Sgn(X) -1) * 1.5708

Inverse Cosecant	Arccosec(X) = Atn(X/Sqr(X * X - 1)) + (Sgn(X) - 1) * 1.5708

Inverse Cotangent	Arccotan(X) = Atn(X) + 1.5708

Hyperbolic Sine	HSin(X) = (Exp(X) - Exp(-X)) / 2

Hyperbolic Cosine	HCos(X) = (Exp(X) + Exp(-X)) / 2

Hyperbolic Tangent	HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X))

Hyperbolic Secant	HSec(X) = 2 / (Exp(X) + Exp(-X))

Hyperbolic Cosecant	HCosec(X) = 2 / (Exp(X) - Exp(-X))

Hyperbolic Cotangent	HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X))

Inverse Hyperbolic Sine	HArcsin(X) = Log(X + Sqr(X * X + 1))

Inverse Hyperbolic Cosine	HArccos(X) = Log(X + Sqr(X * X - 1))

Inverse Hyperbolic Tangent	HArctan(X) = Log((1 + X) / (1 - X)) / 2

Inverse Hyperbolic Secant	HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)

Inverse Hyperbolic Cosecant	HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) +1) / X)

Inverse Hyperbolic Cotangent	HArccotan(X) = Log((X + 1) / (X - 1)) / 2

Logarithm	LogN(X) = Log(X) / Log(N)


ChDir Statement

See Also	Example

Changes the current default directory on a specified drive.

Syntax

ChDir path

Remarks

The argument path is a string expression that identifies which directory becomes the new default directory.  This argument must contain fewer than 128 characters and has the following syntax:

[drive:] [ \ ]directory[\directory] . . .

The argument drive is an optional drive specification; the argument directory is a directory name.  If you omit drive, ChDir changes the default directory on the current drive.

The ChDir statement works like the operating system command CHDIR, except that it cannot be abbreviated to CD like the system command.  Like the operating system command CHDIR, the ChDir statement changes the default directory but not the default drive.  For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

ChDir "D:\TMP"

Use the CurDir[$] function to determine the current directory and the ChDrive statement to change the default drive.


See Also

ChDrive Statement

CurDir, CurDir$ Functions

Dir, Dir$ Functions

MkDir Statement

RmDir Statement


ChDir Statement Example

The example uses ChDir to change the default directory on the current drive.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

CurPath = CurDir	' Get current path.

ChDir "\"

Msg = "The current directory has been changed to "

Msg = Msg & CurDir & NL & NL & "Press OK to change back "

Msg = Msg & "to your previous default directory."

Answer = MsgBox(Msg)	' Get user response.

ChDir CurPath	' Change back to user default.

Msg = "Directory changed back to " & CurPath & "."

MsgBox Msg	' Display results.

End Sub


ChDrive Statement

See Also	Example

Changes the current drive.

Syntax

ChDrive drive

Remarks

The argument drive is a string expression that specifies a new default drive.  It corresponds to an existing drive and must be in the range A to lastdrive, where lastdrive is the maximum drive letter you set in your CONFIG.SYS file.

If you supply a zero-length argument (""), the current drive doesn't change.  If the argument drive is a multiple-character string, ChDrive uses only the first letter.

Use the CurDir[$] function to determine the current drive and directory and the ChDir statement to change the default directory.


See Also

ChDir Statement

CurDir, CurDir$ Functions

MkDir Statement

RmDir Statement


ChDrive Statement Example

The example changes the currently logged drive to the new drive indicated by the letter entered by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

On Error Resume Next

Dim CurPath, Drive, HasColon, Msg, NewDrive, NL	' Declare variables

NL = Chr(10)	' Define newline.

CurPath = CurDir	' Get current path.

If Err = 68 Then	' In case current

Drive = "invalid."	' drive is invalid

Err = 0	' reset error to 0.

Else

Drive = Left(CurPath, 2)	' Get drive letter.

End If

Msg = "Your currently logged drive is " & Drive & NL & NL

Msg = Msg & "Enter the letter of another drive to make the "

Msg = Msg & "logged drive."

NewDrive = InputBox(Msg)	' Prompt for new drive.

HasColon = InStr(1, NewDrive, ":")	' Check for colon.

' If there is no colon, append one to NewDrive.

If Not HasColon Then NewDrive = Left(NewDrive, 1) & ":"

ChDrive NewDrive	' Change drive.

Select Case Err

Case 68	' Device unavailable error.

Msg = "That drive is not available. No drive change "

Msg = Msg & "was made."

Case 71	' Disk not ready error.

Msg = "Close the door on your drive and try again."

Case 5	' Illegal function call.

Msg = "You probably didn't enter a drive letter. No drive "

Msg = Msg & "change was made."

Case Else

Msg = "Drive changed to " & UCase(NewDrive)

End Select

MsgBox Msg	' Display results.

End Sub


Command, Command$ Functions

Example

Returns the argument portion of the command line used to launch Microsoft Visual Basic.

Syntax

Command[$]

Remarks

Command returns a Variant; Command$ returns a String.

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

VB /CMD cmdlineargs

For applications developed with Visual Basic (compiled to an .EXE file), Command[$] returns any argument(s) that appears after the name of the application on the command line.  For example:

myapp  cmdlineargs

In the code window, you can change the text returned by Command[$] by choosing Project from the Options menu.


Command, Command$ Functions Example

The example uses Command to display the arguments on the command line.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

If Command = "" Then	' If no command line.

Msg = "There is currently no command-line string."

Else	' Put command line into message.

Msg = "The command-line string is: '" & Command & "'"

End If

MsgBox Msg	' Display message.

End Sub


CurDir, CurDir$ Functions

See Also	Example

Returns the current path for the specified drive.

Syntax

CurDir[$] [(drive)]

Remarks

CurDir returns a Variant; CurDir$ returns a String.

The argument drive is a string expression that specifies a drive in the range A to lastdrive, where lastdrive is the maximum drive letter you set in your CONFIG.SYS file.

If no drive is specified or if drive is zero-length, CurDir[$] returns the path for the current drive.  This is similar to using the CHDIR command at the system prompt without specifying a path.

An error occurs if the first character in drive lies outside the range A to lastdrive.  An error also occurs if the first character in drive is not a letter, or if it corresponds to a drive that doesn't exist.


See Also

ChDir Statement

ChDrive Statement

MkDir Statement

RmDir Statement


CurDir, CurDir$ Functions Example

The example uses CurDir to return the name of the current directory.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "The current directory is: "

Msg = Msg & NL & CurDir	' Get current directory.

MsgBox Msg	' Display message.

End Sub


Dir, Dir$ Function

See Also	Example

Returns the name of a file or directory that matches a specified pattern and file attribute.  Also can return the volume label of a drive .

Syntax

Dir[$] [(filespec [,attrmask])]

Remarks

Dir returns a Variant; Dir$ returns a String.

The Dir[$] function has these parts:

Part	Description

filespec	String expression that specifies a path or file name.  The path and file name can include a drive specification and any valid wildcard characters.

attrmask	Specifies the attributes (Hidden, System, etc) of the file names you want returned.  If attrmask is not specified, Dir[$] returns all normal files (those without hidden, system, directory, or volume label attributes) that match filespec.  You can add to the list of file names returned by Dir[$] by specifying a value for attrmask that includes directories, and hidden or system files.  In addition, you can specify that Dir[$] return the label of the volume whose drive is specified as part of filespec, or the currently selected drive if no drive is explicitly specified.  If attrmask specifies the volume label, all other attributes are ignored.  The attrmask is created by summing the values, shown in the table below, to identify the particular file attribute(s) you want included.

Symbolic Constant	Value	Meaning
ATTR_NORMAL	0	Normal files
ATTR_HIDDEN	2	Hidden files
ATTR_SYSTEM	4	System files
ATTR_VOLUME	8	Volume label
ATTR_DIRECTORY	16	Directory
Note	Symbolic constants for attribute definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.

You must specify filespec the first time you call the function, or an error occurs.  If you also specify file attributes, attrmask can only be included in the same call to Dir[$] where filespec is included.  Dir[$] returns the first file name that matches filespec.  To get any additional file names that match filespec, call Dir[$] again with no arguments.  When no more file names match, Dir[$] returns a zero-length String or Variant of VarType 8.  Once a zero-length String or Variant has been returned, you must again use a filespec argument in subsequent calls or an error occurs.

Note	You can change to a new filespec without retrieving all of the file names that match the current filespec.  However, you cannot recursively call the Dir[$] function.

Tip	Because file names are retrieved in no particular order, you may want to store returned file names in an array and then sort the array.


See Also

ChDir Statement

CurDir, CurDir$ Functions


Dir, Dir$ Functions Example

The example uses Dir to determine all the subdirectories on drive C.  To try this example, paste the code into the Declarations section of a form containing a list box named List1.  Then press F5 and click the form.

Const ATTR_DIRECTORY = 16	' Declare form constant.

Sub Form_Click ()

ListSubDirs "C:\"	' Call ListSubDirs

End Sub

Sub ListSubDirs (Path)

Dim Count, D(), I, DirName	' Declare variables.

DirName = Dir(Path, ATTR_DIRECTORY)	' Get first directory name.

'Iterate through PATH, caching all subdirectories in D()

Do While DirName <> ""

If DirName <> "." And DirName <> ".." Then

If GetAttr(Path + DirName) = ATTR_DIRECTORY Then

If (Count Mod 10) = 0 Then

ReDim Preserve D(Count + 10)	' Resize the array.

End If

Count = Count + 1	' Increment counter.

D(Count) = DirName

End If

End If

DirName = Dir	' Get another directory name.

Loop

' Now recursively iterate through each cached subdirectory.

For I = 1 To Count - 1

List1.AddItem Path & D(I)	' Put name in list box.

ListSubDirs Path & D(I) & "\"

Next I

End Sub


Environ, Environ$ Function

Example

Returns the string associated with an operating system environment variable.

Syntax 1

Environ[$](environmentstring)

Syntax 2

Environ[$](n)

Remarks

Environ returns a Variant; Environ$ returns a String.

The Environ[$] function has these parts:

Part	Description

environmentstring	String expression containing the name of an environment variable.

n	Numeric expression corresponding to the nth string of the environment-string table. The argument n can be any numeric expression, but it is rounded to an integer before it is evaluated.

If the environment variable name you specify cannot be found in the environment-string table, a zero-length String or Variant of VarType 8 is returned.  Otherwise, Environ[$] returns the text assigned to the specified environment variable (the text following the equal sign in the environment-string table for that environment variable.)

If you specify a numeric argument (n), the nth string of the environment-string table is returned.  In this case, Environ[$] returns all of the text, including environmentstring.  If the nth string doesn't exist, Environ[$] returns a zero-length String or Variant of VarType 8.


Environ, Environ$ Functions Example

The example uses Environ to supply the entry number and length of the PATH statement from the environment-string table.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim EnvString, I, Msg, PathLen	' Declare variables.

Indx = 1	' Initialize index to 1.

Do

EnvString = Environ(Indx)	' Get environment variable.

If Left(EnvString, 5) = "PATH=" Then	' Check PATH entry.

PathLen = Len(Environ("PATH"))	' Get length.

Msg = "PATH entry = " & Indx & " and length = " & PathLen

Exit Do

Else

Indx = Indx + 1	' Not PATH entry, so increment.

End If

Loop Until EnvString = ""

If PathLen > 0 Then

MsgBox Msg	' Display message.

Else

MsgBox "No PATH environment variable exists."

End If

End Sub


Kill Statement

See Also	Example

Deletes files from a disk.

Syntax

Kill filespec

Remarks

The Kill statement is similar to the operating system commands ERASE and DEL.

Kill only deletes disk files.  To delete directories, use the Visual Basic RmDir statement.

Using Kill to delete a file that is currently open by Visual Basic produces an error.

Caution	Be extremely careful using wildcard characters with Kill.  You can delete more files than you intended.


See Also

RmDir Statement


Kill Statement Example

The example uses Kill to remove a file the user specifies.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Ansr, DelFile, Msg	' Declare variables.

On Error GoTo Errhandler	' Set up error handler.

DelFile = UCase(InputBox("Enter file name you want deleted."))

If Len(DelFile) Then	' Check for entry.

Ansr = MsgBox("Sure you want to delete " & DelFile & "?", 4)

If Ansr = 6 Then	' User chose "Yes."

Msg = "Deleting " & DelFile & " from your disk."

Kill DelFile	' Delete file from disk.

Else

Msg = DelFile & " was not deleted."

End If

Else

Msg = "You didn't enter a file name."

End If

MsgBox Msg	' Display message.

End

Errhandler:

If Err = 53 Then	' Error 53 is "File not Found".

Msg = "Sorry, the file you named could not be found."

Else

Msg = "Sorry, unable to delete file."

End If

Resume Next

End Sub


MkDir Statement

See Also	Example

Creates a new directory.

Syntax

MkDir pathname

Remarks

The argument pathname is a string expression that specifies the name of the directory to be created.  This argument must contain fewer than 128 characters and has the following syntax:

[drive:] [ \ ]directory[\directory] . . .

The argument drive is an optional drive specification; the argument directory is a directory name.

The MkDir statement works like the operating system command MKDIR, except that it cannot be abbreviated to MD like the system command.

If you use MkDir to create a directory whose name contains an embedded space, you may be able  to access it with some applications, but you can't remove it using standard operating system commands.  To remove such a directory, use the RmDir statement from within Visual Basic or a Visual Basic application.


See Also

ChDir Statement

CurDir, CurDir$ Functions

RmDir Statement


MkDir Statement Example

The example uses the MkDir statement  to create a \TMP subdirectory off the root directory of the currently logged drive.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Ansr, CurDrv, Msg, TmpPath	' Declare variables.

On Error Resume Next	' Set up error handler.

CurDrv = Left(CurDir, 2)	' Get current drive letter.

TmpPath = UCase(CurDrv + "\tmp")	' Make path specification.

MkDir TmpPath	' Make new directory.

If Err = 75 Then	' Check if directory exists.

Msg = TmpPath & " directory already exists."

Else

Msg = TmpPath & " directory created."

End If

Msg = Msg & " Do you want it removed?"

Ansr = MsgBox(Msg, 4)	' Display message and get

If Ansr <> 7 Then RmDir TmpPath	' user response.

End Sub


Name Statement

See Also	Example

Changes the name of a disk file or directory.

Syntax

Name oldfilespec As newfilespec

Remarks

The Name statement is similar to the operating system RENAME command, but Name can also be used to change the name of a directory.  Using Name, you can move a file from one directory to another, but you can't move a directory.

The arguments oldfilespec and newfilespec are string expressions, each of which contains a file name and an optional path.  If the path in newfilespec exists and is different from the path in oldfilespec, the Name statement moves the file to the new directory and renames the file if necessary.  If newfilespec and oldfilespec have different paths and the same file name, Name moves the file to the new directory and leaves the file name unchanged.

The file specified by oldfilespec must exist and the file specified by newfilespec cannot already exist.  Both newfilespec and oldfilespec must be on the same drive.

Using Name on a file currently open by Visual Basic produces an error.  You must close an open file before renaming it.


See Also

Kill Statement


Name Statement Example

The example moves a file from one directory to another and renames it at the same time.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FName1, FName2, Msg, NL, TestDir	' Declare variables.

NL = Chr(10)	' Define newline.

FName1 = "NMSTMTX.DAT"	' Define filenames.

FName2 = "NMSTMTY.DAT"

TestDir = "\TEST.DIR"	' Test directory name.

Open FName1 For Output As #1	' Create a test file.

Print #1, "test data"	' Put something in file.

Close #1

MkDir TestDir	' Make test directory.

Name FName1 As TestDir & "\" & FName2	' Move and rename.

Msg = "A new file, " & FName1 & " has been created "

Msg = Msg & "in " & CurDir$ & ". Once created, it was "

Msg = Msg & "moved to " & TestDir & " and renamed "

Msg = Msg & FName2 & "." & NL & NL

Msg = Msg & "Choose OK to remove the test data file and "

Msg = Msg & "directory."

MsgBox Msg	' Display message.

Kill TestDir & "\" & FName2	' Remove file from disk.

RmDir TestDir	' Remove test directory.

End Sub


RmDir Statement

See Also	Example

Removes an existing directory.

Syntax

RmDir path

Remarks

The argument path is a string expression that specifies the name of the directory to be removed.  This argument must have fewer than 128 characters and has the following syntax:

[drive:] [ \ ]directory[\directory] . . .

The argument drive is an optional drive specification; the argument directory is a directory name.

The RmDir statement works like the operating system command RMDIR, except that it cannot be abbreviated to RD like the system command.  If the directory to be removed contains anything except the working directory ( '.' ) and the parent directory ( '..' ), an error occurs.


See Also

ChDir Statement

CurDir, CurDir$ Functions

MkDir Statement


RmDir Statement Example

The example uses the RmDir statement to remove a previously created directory at the user's request.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const MB_YESNO = 4	' Yes and No buttons

Const IDNO = 7	' No response

Dim Ansr, CurDrv, Msg, TmpPath	' Declare variables.

On Error Resume Next	' Set up error handler.

CurDrv = Left(CurDir, 2)	' Get current drive letter.

TmpPath = UCase(CurDrv + "\tmp")	' Make path specification.

MkDir TmpPath	' Make new directory.

If Err = 75 Then	' Check if directory exists.

Msg = TmpPath & " directory already exists."

Else

Msg = TmpPath & " directory created."

End If

Msg = Msg & " Do you want it removed?"

Ansr = MsgBox(Msg, MB_YESNO)	' Display message box and get

If Ansr <> IDNO Then RmDir TmpPath	' user response.

End Sub


Err, Erl Functions

See Also	Example

Returns error status.

Syntax

Err

Erl

Remarks

After an error occurs, the Err function returns an Integer run-time error code identifying the error.  The Erl function returns a Long that is the line number of the line in which the error occurred or the line most closely preceding it.

Because Err and Erl return meaningful values only after an error has occurred, they are usually used in error-handling routines to determine the error and the corrective action.  Both Err and Erl are reset to 0 after any form of the Resume or On Error statement and after an Exit Sub or Exit Function statement within an error-handling routine.

Caution   If you set up an error handler using On Error GoTo and that error handler calls another procedure, the value of Err and Erl may be reset to 0.  To make sure that the value doesn't change, assign the values of Err or Erl to variables before calling another procedure or before executing Resume, On Error, Exit Sub, or Exit Function.

You can directly set the value returned by the Err function using the Err statement.  You can set the values for both Err and Erl indirectly using the Error statement.

The Erl function returns only a line number, not a line label, located at or before the line producing the error.  Line numbers greater than 65,529 are treated as line labels and can't be returned by Erl.  If your procedure has no line numbers, or if there is no line number before the point at which an error occurs, Erl returns 0.


See Also

Err Statement

Error Statement

On Error Statement

Resume Statement

Trappable Errors


Err, Erl Functions Example

The example shows an error-handling routine.  If there are no additional errors, Err returns error number 11 (Division by zero) and Erl returns line 1030.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

1000  Dim A, B, C	' Declare variables.

1010  On Error GoTo ErrHandler	' Set up an error handler.

1020  B = 1

1030  A = B \ C	' Cause a "Division by zero" error.

1040  Exit Sub

ErrHandler:	' Error handler line label.

MsgBox "Error number " & Err & " occurred at line " & Erl

Resume Next

End Sub


Err Statement

See Also	Example

Sets Err to a specific value.

Syntax

Err = n

Remarks

The argument n is either an integer between 1 and 32,767, inclusive, that specifies a run-time error code or 0, which means no run-time error has occurred.

When running an application, Visual Basic uses Err to record whether or not a run-time error has occurred and what the error was.

Use the Err statement to set Err to a nonzero, integer value to communicate error information between procedures.  For example, you might use one of the run-time error codes not used by Visual Basic as an application-specific error code.  To determine which error codes are being used, use the Error[$] function and/or the Error statement.  You can create application-specific user-defined errors by working down from error code 32,767.

You can also set Err to 0 by using any form of the Resume or On Error statement or by executing an Exit Sub or Exit Function statement within an error handler.  In addition, the Error statement can set Err to any value to simulate any run-time error.


See Also

Err, Erl Functions

Error, Error$ Functions

Error Statement


Err Statement Example

As the example shows, with On Error Resume Next, errors are often handled in the lines of code immediately following the line where an error can occur.  Once the error has been handled, the Err statement clears the error by setting Err to 0 so subsequent error-handling code isn't inadvertently executed for an earlier error.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileName	' Declare variable.

On Error Resume Next	' Set up error handler.

FileName = InputBox("Enter a file name: ")	' Get file name.

Do

Err = 0	' Clear any error.

Open FileName For Input As #1 	' Open file.

Select Case Err	' Handle error, if any.

Case 0	' No error.

MsgBox UCase(FileName) & " was found."	' File found.

Case 53, 75, 76	' Assorted file errors.

FileName = InputBox("File was not found. Try again.")

Case 52, 64	' Bad file name or number.

FileName = InputBox("File name was invalid. Try again.")

Case 68	' Device unavailable.

FileName = InputBox("Device is not available. Try again.")

Case 71	' Drive not ready.

MsgBox "Close the drive door."

Case Else	' Handle other cases.

MsgBox "ERROR: Cannot continue!"	' All fatal errors.

Stop

End Select

Loop Until Err = 0

Close #1

End Sub


Error, Error$ Function

See Also	Example

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

Syntax

Error[$][(errorcode)]

Remarks

Error returns a Variant; Error$ returns a String.

The argument errorcode must be an integer between 1 and 32,767, inclusive.  If errorcode is omitted, the message string corresponding to the most recent run-time error is returned.  If errorcode is not defined in Visual Basic, the returned message string is User-defined error.

Some error messages use internal variables to provide specific information about an error.  When an error occurs, words appropriate to the context of the error are substituted in the error message string.  Under normal circumstances, the following error message appears with a control array element index number inserted between the single quotation marks:

Control array element '11' doesn't exist

However, when you use Error[$] to return an error message for a specified error code, there is no context for that error message and the appropriate text can't be inserted.  As a result, the message string returned by Error[$] contains no context-specific information between the single quotation marks.  A space is inserted in lieu of the actual context information.

If Error[$] is called with no argument, it returns the message string for the most recent run-time error.  If a run-time error has occurred, the returned message string includes substitutions appropriate to the context of the error.  If no run-time error has occurred, Error[$] returns a zero-length string ("").

The Err function returns the error code for the most recent run-time error.  Therefore, the following lines are equivalent except that in the first case, the text placed in A includes appropriate substitutions, and in the second case, no substitutions are made.

A = Error

A = Error(Err)


See Also

Err, Erl Functions

Error Statement

Trappable Errors


Error, Error$ Functions Example

The example uses the Error function to display error messages associated with user-input error numbers.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, UserError	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

NL = Chr(10)	' Define newline.

Msg = "Please enter an error number to see the associated error"

Msg = Msg & " message."

UserError = InputBox(Msg)

Error UserError	' Simulate error occurrence.

Exit Sub

ErrorHandler:	' Error handler line label.

Msg = "The error message for error number "

Msg = Msg & Err & " is:" & NL & NL

Msg = Msg & """" & Error(Err) & """"

MsgBox Msg	' Display message.

Resume Next

End Sub


Error Statement

See Also	Example

Simulates the occurrence of an error; can be used to generate a user-defined error.

Syntax

Error errorcode

Remarks

The argument errorcode must be an integer between 1 and 32,767, inclusive.  If errorcode is an error code defined by Visual Basic, the Error statement simulates the occurrence of that error; that is, it sets the value of Err to errorcode.

To define your own error code, use a value that is greater than any used by the standard Visual Basic error codes.  You can create application-specific user-defined errors working down from error code 32,767.

If an Error statement is executed when no error-handling routine is enabled, Visual Basic displays an error message and stops program execution.  If the Error statement specifies an error code that is not used by Visual Basic, the message User-defined error is displayed.


See Also

Err, Erl Functions

On Error Statement

Resume Statement

Trappable Errors


Error Statement Example

The example uses the Error statement to simulate the occurrence of an error so that the error handler is invoked and the associated error message is displayed.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, UserError	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

NL = Chr(10)	' Define newline.

Msg = "Please enter an error number to see the associated error"

Msg = Msg & " message."

UserError = InputBox(Msg)

Error UserError	' Simulate error occurrence.

Exit Sub

ErrorHandler:	' Error handler line label.

Msg = "The error message for error number "

Msg = Msg & Err & " is:" & NL & NL

Msg = Msg & """" & Error(Err) & """"

MsgBox Msg	' Display message.

Resume Next

End Sub


On Error Statement

See Also	Example

Enables an error-handling routine and specifies the location of the routine within a procedure; can be used to disable an error-handling routine.

Syntax

On Error { GoTo line | Resume Next | GoTo 0 }

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, Visual Basic generates an error message and stops program execution.

The On Error statement has these parts:

Part	Description

GoTo line	Enables the error-handling routine that starts at line (a line label or a line number).  Thereafter, if a run-time error occurs, program control branches to line.  The specified line must be in the same procedure as the On Error statement.  If it isn't, a compile-time error occurs.

Resume Next	Specifies that when a run-time error occurs, control goes to the statement immediately following the statement in which the error has occurred. In other words, the code continues to execute.  You can use the Err function in subsequent lines of code to obtain the run-time error number.

GoTo 0	Disables any enabled error handler in the current procedure.

An error handler is enabled when it is referred to by an On Error GoTo line statement.  Once an error handler is enabled, any run-time error causes program control to jump to the enabled error-handling routine and makes the error handler active.  An error handler remains active from the time a run-time error has been trapped until a Resume, Exit Sub, or Exit Function statement is executed in the error handler.

If an error occurs while an error handler is active (between the occurrence of the error and the execution of a Resume, Exit Sub, or Exit Function statement), the current procedure's error handler cannot handle the error.  If the calling procedure has an enabled error handler, control is returned to the calling procedure and its error handler is activated to handle the error.  If the calling procedure's error handler also is active, control is passed back through any previous calling procedures until an inactive error handler is found.  If no inactive error handler is found, the error is fatal at the point at which it actually occurred.  Each time the error handler passes control back to the calling procedure, that procedure becomes the current procedure.  Once an error is handled by an error handler in any procedure, program execution resumes in the current procedure at the point designated by the Resume statement.

Notice that an error-handling routine is not a Sub or Function procedure. It is a block of code marked by a line label or line number.

Error-handling routines rely on the value in Err to determine the cause of the error.  The error-handling routine should test or save this value before any other error can occur or before a procedure that could cause an error is called.  The value in Err reflects only the most recent error.  You can use the Error[$] function to return the error message associated with any given run-time error number returned by Err.

On Error Resume Next causes program execution to continue with the statement immediately following the statement that caused the run-time error.  This allows your program to continue despite a run-time error and then check for the cause of the error.  This also lets you build the error-handling routine in line with the procedure rather than transferring control to another location within the procedure.

On Error GoTo 0 disables error handling in the current procedure.  It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0.  Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from executing when no error has occurred, place an Exit Sub or Exit Function statement immediately ahead of the error-handling routine, as in the following example:

Sub InitializeMatrix(Var1, Var2, Var3, Var4)

On Error GoTo ErrorHandler

...

Exit Sub

ErrorHandler:

...

Resume Next

End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to partition it from the normal execution flow of the procedure.  This is by no means the only solution.  Error-handling code can be placed anywhere in a procedure.


See Also

Err, Erl Functions

Error, Error$ Functions

Resume Statement

Trappable Errors


On Error Statement Example

The example uses the On Error statement to set up error handling in a procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Drive, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This demo attempts to open a file that does not exist on a "

Msg = Msg & "drive that may not exist. When the operation fails, "

Msg = Msg & "the ErrorHandler routine will display a message box "

Msg = Msg & "that indicates what error occurred."

MsgBox Msg	' Display opening message.

Drive = Chr(Int((26) * Rnd + 1) + 64)	' Make random drive letter.

Open Drive & ":\TEST\X.DAT" For Input As #1	' Try to open file.

Close #1	' Close the file.

Exit Sub	' Exit before entering

' error  handler.

ErrorHandler:	' Error handler line label.

Select Case Err

Case 53: Msg = "ERROR 53: That file doesn't exist."

Case 68: Msg = "ERROR 68: Drive " & Drive & ": not available."

Case 76: Msg = "ERROR 76: That path doesn't exist."

Case Else: Msg = "ERROR " & Err & " occurred."

End Select

MsgBox Msg	' Display error message.

Resume Next	' Resume procedure.

End Sub


Resume Statement

See Also	Example

Resumes program execution after an error-handling routine is finished.

Syntax

Resume { [0] | Next | line}

Remarks

The various forms of the Resume statement redirect program flow as described below:

Statement	Description

Resume [0]	Program execution resumes with the statement that caused the error or at the most recently executed call out of the procedure containing the error-handling routine.

Resume Next	Execution resumes with the statement immediately following the one that caused the error or with the statement immediately following the most recently executed call out of the procedure containing the error-handling routine.

Resume line	Execution resumes at line, which is a line label or line number.  The argument line must be in the same procedure as the error handler.

Where execution resumes is determined by the location of the error handler in which the error is trapped, not necessarily by the location of the error itself.

The following table summarizes where a program resumes execution when the Resume [0] statement is used:

Where error occurs	Where program resumes

Same procedure as error handler	Statement that caused the error

Different procedure from error handler	Statement that last called out of the procedure containing the error handler

If you use a Resume statement anywhere except in an error-handling routine, an error occurs.

When an error-handling routine is active and the end of the procedure (an End Sub or End Function statement) is encountered before a Resume statement is executed, an error occurs because a logical error is presumed to have been made inadvertently.  However, if an Exit Sub or Exit Function statement is encountered while an error handler is active, no error occurs because it is considered a deliberate redirection of program flow.


See Also

On Error Statement

Trappable Errors


Resume Statement Example

The example uses Resume Next  to end error handling in a procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Drive, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This demo attempts to open a file that does not exist on a "

Msg = Msg & "drive that may not exist. When the operation fails, "

Msg = Msg & "the ErrorHandler routine will display a message box "

Msg = Msg & "that indicates what error occurred."

MsgBox Msg	' Display opening message.

Drive = Chr(Int((26) * Rnd + 1) + 64)	' Make random drive letter.

Open Drive & ":\TEST\X.DAT" For Input As #1	' Try to open file.

Close #1	' Close the file.

Exit Sub	' Exit before entering

' error  handler.

ErrorHandler:	' Error handler line label.

Select Case Err

Case 53: Msg = "ERROR 53: That file doesn't exist."

Case 68: Msg = "ERROR 68: Drive " & Drive & ": not available."

Case 76: Msg = "ERROR 76: That path doesn't exist."

Case Else: Msg = "ERROR " & Err & " occurred."

End Select

MsgBox Msg	' Display error message.

Resume Next	' Resume procedure.

End Sub


Close Statement

See Also	Example

Concludes input/output (I/O)to a file.

Syntax

Close [[#]filenumber] [,[#]filenumber] . . .

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression as long as it evaluates to the number of an open file.

A Close statement with no arguments closes all open files..

The association of a file with filenumber ends when a Close statement is executed.  You then can reopen the file using the same or a different file number, or you can reuse the file number to open a different file.

Using a Close statement for a file that was opened for Output or Append writes the final buffer of output to the operating system buffer for that file.  Close releases all Visual Basic buffer space associated with the closed file.

The Close statement complements the Open statement.


See Also

End Statement

Open Statement

Reset Statement

Stop Statement


Close Statement Example

The example uses Close to close all three files opened for Output.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

Make3Files	' Create data files.

Msg = "Several test files have been created on your disk. "

Msg = Msg & "Choose OK to remove the test files."

MsgBox Msg

Kill "TEST?"	' Remove data files from disk.

End Sub

Sub Make3Files ()

Dim I, FNum, FName	' Declare variables.

For I = 1 To 3

FNum = FreeFile	' Determine next file number.

FName = "TEST" & FNum

Open FName For Output As FNum	' Open file.

Print #I, "This is a test."	' Write string to file.

Next I

Close	' Close all files.

End Sub


EOF Function

See Also	Example

Returns a value during file input that indicates whether the end of a file has been reached.

Syntax

EOF(filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.

The EOF function returns True if the end of a file has been reached, False if it has not.  Use the EOF function with sequential files to test for the end of a file.  This helps you avoid the error that occurs when you attempt to get input past the end of a file.

When used with Random or Binary files, EOF returns True if the last executed Get statement was unable to read an entire record; otherwise, it returns False.


See Also

Loc Function

LOF Function

Open Statement


EOF Function Example

The example uses the EOF function to detect the end of a sequential file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NL, TestVar, Msg	' Declare variables.

NL = Chr(10)	' Define newline

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open file for input.

Do While Not EOF(1)	' Check for end of file.

Input #1, TestVar	' Read data.

Loop

Close #1	' Close file.

Msg = "The last value read from the data file was "

Msg = Msg & TestVar & "." & NL

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display results.

Kill "TESTFILE"	' Delete file from disk.

End Sub

Sub MakeDataFile ()

Dim I	' Declare variable.

Open "TESTFILE" For Output As #1	' Open file.

For I = 0 To 200	' Generate random values

Print #1, Int((100) * Rnd)	' from 0 to 99.

Next I

Close #1	' Close file.

End Sub


FileAttr Function

See Also	Example

Returns file mode or operating system file handle information about an open file.

Syntax

FileAttr(filenumber, attribute)

Remarks

The FileAttr function has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

attribute	Number that indicates the type of information to return about the file.  Use 2 to return the operating system handle for the file.  Use 1 to return one of the following values used to indicate the file's mode:

Return value	Mode

1	Input

2	Output

4	Random

8	Append

32	Binary


See Also

GetAttr Function

Open Statement

SetAttr Statement


FileAttr Function Example

The example uses FileAttr to report the file handle and mode of an open file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileNum, Handle, Mode, Msg	' Declare variables.

FileNum = FreeFile	' Get available file number.

Open "TESTFILE" For Append As FileNum	' Create sample data file.

Handle = FileAttr(FileNum,2)	' Get file handle.

Select Case FileAttr(FileNum,1)	' Determine mode.

Case 1 : Mode = "Input"

Case 2 : Mode = "Output"

Case 4 : Mode = "Random"

Case 8 : Mode = "Append"

Case 32 : Mode = "Binary"

End Select

Close FileNum	' Close file.

Msg = "The file using DOS file handle " & Handle

Msg  = Msg & " was opened for " & Mode

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Delete zero-length file.

End Sub


FreeFile Function

See Also	Example

Returns the next valid unused file number.

Syntax

FreeFile [( )]

Remarks

Use FreeFile when you need to supply a file number and you want to ensure that the file number is not already in use.


See Also

Open Statement


FreeFile Function Example

The example uses the FreeFile function to return the next available file number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NL, FileNum, Msg	' Declare variables.

NL = Chr(10)	' Define newline.

FileNum = FreeFile	' Get unused file number.

Open "TESTFILE" For Output As FileNum	' Create sample data file.

Close FileNum	' Close file.

Msg = "The file number returned by the FreeFile function was "

Msg = Msg & FileNum & "." & NL & NL

Msg = Msg & "Choose OK to remove the created test file."

MsgBox Msg	' Display results.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Get Statement

See Also	Example

Reads from a disk file into a variable.

Syntax

Get [#] filenumber,[recordnumber],variablename

Remarks

The Get statement has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

recordnumber	The largest possible recordnumber is 2^31 - 1, or 2,147,483,647.  For files opened in Random mode, recordnumber is the number of the record to be read.  For files opened in Binary mode, recordnumber is the byte position at which reading starts.  The first byte in a file is at position 1, the second byte is at position 2, and so on.  If you omit recordnumber, the next record or byte (the one following the last Get or Put statement or the one pointed to by the last Seek function) is read from.  If you omit recordnumber, you must still include the commas.  For example:
Get #4,,FileBuffer

variablename	Name of the variable used to receive input from the file.  Any variable can be used except object variables and array variables (variables that describe an entire array).  However, you can use a variable that describes a single element of an array.

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

If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get still reads subsequent records on record-length boundaries.  The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer.  Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have record length match the length of the data being written.

If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing string length and then reads the data that goes into the variable.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

If the variable being read into is a numeric Variant (VarType 0-7), Get reads 2 bytes identifying the VarType of the Variant and then reads the data that goes into the variable.  For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

If the variable being read into is a String Variant (VarType 8), Get reads 2 bytes identifying the VarType, then reads 2 bytes indicating the length of the string, and then reads the string data.  The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.

If the variable being read into is any other type of variable (not a variable-length string or a Variant), Get reads only the variable data.  The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read.

Elements of user-defined types are read using Get as if each were being read individually except that there is no padding between elements.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements.

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

In Binary mode, the Len clause in the Open statement has no effect.  Get reads all variables from disk contiguously, that is, with no padding between records.

Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor.  The number of bytes read equals the number of characters already in the string.  For example, the following statements read 10 bytes from file number 1:

VarString$ = String$(10," ")

Get #1, , VarString$


See Also

Open Statement

Put Statement

Type Statement


Get Statement Example

The example uses the Get statement to read data from a disk file into a variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Clientname As String * 20	' Declare variables.

Dim Indx, Max, Msg, NL

NL = Chr(10)	' Define newline.

' Make a sample random-access file using the Put statement.

Msg = "Enter a name, using whatever form you like." & NL & NL

Msg = Msg & "Press 'Enter' with no name to conclude entry."

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

ClientName = InputBox(Msg)	' Get user input.

Do While ClientName <> String(20, " ")

Put #1, , ClientName	' Write to file.

ClientName = InputBox(Msg)	' Get user input.

Loop

' Read the sample random-access file using the Get statement.

Max = Loc(1)

If Max = 0 Then	' Check if records exist.

Msg = "Your file contains no names." & NL

Else

Msg = "Your file contains the following names:" & NL & NL

End If

For Indx = 1 To Max

Get #1, Indx, ClientName	' Read from file.

Msg = Msg & ClientName & NL

Next Indx

Close #1	' Close file.

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Input # Statement

See Also	Example

Reads data from a sequential file and assigns the data to variables.

Syntax

Input # filenumber, variablelist

Remarks

The Input statement has these parts:

Part	Description

filenumber	Number used to open the file with the Open statement.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is required.

variablelist	Comma-delimited list of the variables that are assigned values read from the file.

A variable in variablelist can't be an array variable but can be a variable that describes an element of an array.  A variable also can't be a user-defined type variable but can be an element.  All other variables are allowed, except object variables.

Data items in a file must appear in the same order as the variables in variablelist.  Be sure to match data in the file with variables of the proper data type: string data into String or Variant variables, numeric data into numeric or Variant variables, and uniquely Variant data (dates and Null values) into Variant variables.  Failure to match the data with a variable of the correct data type may produce unpredictable results.

When a variable in variablelist is numeric, the first nonspace character encountered is assumed to be the start of a number.  The end of the number is assumed when a space, a comma, or the end of a line is encountered.  Blank lines are input as zero.  If the data is not valid numeric data, zero is the value assigned to the variable.

When a variable in variablelist is a String, the first nonspace character encountered is assumed to be the start of a character string.  If that first character is a double quotation mark ("), it is ignored, but all characters following it (including spaces and commas) up to the next double quotation mark are input into the String variable.  For strings not delimited by double quotation marks, the end of a string is assumed when a comma, a space, or the end of a line is encountered.  Blank lines are input as zero-length strings.

When the variablelist variable is a Variant, the first nonspace character is assumed to be the start of the data.  The following rules determine how the actual data is treated:

If the input data is a valid number, the Variant is set to an appropriate numeric VarType.

If the input data consists of no data, only a delimiting comma or a blank line, the Variant is assigned VarType 0 (Empty).

If the input data is the literal #NULL#, the Variant is assigned VarType 1 (Null).

If the input data is a date literal (a date of the form #yyyy-mm-dd hh:mm:ss#), the Variant is assigned VarType 7 (Date).  Note that when either the date portion or the time portion is present, the other portion is optional.

If the input data is not a valid number, is not Empty or Null, and is not a valid date, it is input as a String and the Variant is assigned VarType 8.

If the end of file is reached while a data item is being input, the input is terminated and an error occurs.


See Also

Input, Input$ Function

Write # Statement


Input # Statement Example

In this example, the Input # statement reads a non-numeric value from a file into a variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileData, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open to read file.

Do While Not EOF(1)

Input #1, FileData	' Read line of data.

Msg = Msg & FileData & NL	' Construct message from data.

Loop

Close #1	' Close file.

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub

Sub MakeDataFile

Open "TESTFILE" For Output As #1	' Open to write file.

Print #1, "This is test line 1."	' Print some data.

Print #1, "This is test line 2."

Close #1	' Close file.

End Sub


Input, Input$ Function

See Also	Example

Returns characters read from a sequential file.

Syntax

Input[$](n,[#]filenumber)

Remarks

Input returns a Variant; Input$ returns a String.

The Input[$] function has these parts:

Part	Description

n	Number of characters (bytes) to read from the file.  Must be less than 65,535.

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

The Input[$] function can only be used with files opened in Input or Binary mode.

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


See Also

Input # Statement


Input, Input$ Functions Example

The example uses the Input function to read one character at a time from a file.  When an ANSI character code 10 (linefeed) is encountered, the entire line of text is displayed in a message box.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Char, FileName, TextData	' Declare variables.

FileName = InputBox("Enter filename.")	' Get file name.

If Len(FileName) Then

Open FileName For Input As #1	' Open file.

Do While Not EOF(1)

Char = Input(1, #1)	' Get one character.

If Char <> Chr(10) Then	' If not linefeed.

TextData = TextData & Char

Else	' If linefeed,

MsgBox TextData	' display line.

TextData = ""	' Clear line.

End If

Loop	' Loop if not end of file.

Close # 1	' Close file.

End If

End Sub


Line Input Statement

See Also	Example

Reads a line from a sequential file into a String or Variant variable.

Syntax

Line Input # filenumber, variablename

Remarks

The Line Input # statement has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is required.

variablename	Name of the variable used to receive a line of text from the file.

The Line Input # statement reads all characters in a sequential file up to a carriage return.  It then skips over the carriage-return/linefeed sequence.

Line Input # reads a text file one line at a time.


See Also

Input # Statement


Line Input # Statement Example

The example uses the Line Input # statement to read and display the first line in the CONFIG.SYS file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Drive, FileName, Msg, NL, TextLine	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "Which drive does your operating system boot from?"

Drive = UCase(Left(InputBox(Msg), 1))	' Get user input.

If Drive = "C" or Drive = "A" Then

FileName = Drive & ":\CONFIG.SYS"

If Dir(FileName) <> "" Then	' Check if file exists.

Open FileName For Input As #1	' If it does, open it.

Line Input #1, TextLine	' Get complete line.

Close #1	' Close file.

Msg = "The first line of your CONFIG.SYS file is:"

Msg = Msg & NL & TextLine & "."

Else	' No CONFIG.SYS.

Msg = "Could not find a CONFIG.SYS file on drive "

Msg = Msg & Drive & ":"

End If

Else

Msg = "You did not provide a valid boot drive. Systems "

Msg = Msg & "normally boot from either A: or C: drive."

End If

MsgBox Msg	' Display message.

End Sub


Loc Function

See Also	Example

Returns the current position within an open file.

Syntax

Loc(filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.  For Random files, the Loc function returns the number of the last variable read from or written to the file.  For sequential files, Loc returns the current byte position in the file divided by 128.  For Binary mode files, Loc returns the position of the last byte read or written.


See Also

EOF Function

LOF Function

Open Statement


Loc Function Example

The example uses the Loc function to report the current position within an open data file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL, PresentLoc, Tmp	' Declare variables

NL = Chr(10)	' Define newline.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open file just created.

For I = 1 To 50

Input #1, Tmp	' Read some data, and discard.

Next I

PresentLoc = Loc(1)	' Get location within file.

Close #1	' Close file.

Msg = "50 data elements have been read from a file of 500. "

Msg = Msg & "The present location within the TESTFILE file is "

Msg = Msg & PresentLoc & "." & NL & NL

Msg = Msg & "Choose OK to remove the sample data file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Delete file from disk.

End Sub

Sub MakeDataFile ()

Dim I	' Declare variable.

Open "TESTFILE" For Output As #1	' Open file for output.

For I = 1 To 500	' Generate random values.

Print #1, Int(501 * Rnd)	' Put data in file.

Next I

Close #1	' Close file.

End Sub


Lock, Unlock Statements

See Also	Example

Control access by other processes to all or part of an opened file.

Syntax

Lock [#]filenumber [,{record | [start] To end} ]
. . .

Unlock [#]filenumber [,{record | [start] To end} ]

Remarks

The Lock and Unlock statements are used in networked environments in which several processes might need access to the same file.  The arguments to Lock and Unlock must match exactly.  The Lock and Unlock statements have these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

record	Number of the record or byte to lock.  It can be any number from 1 through 2,147,483,647 (equivalent to 2^31-1).  A record can be up to 65,535 bytes long.

start	Number of the first record or byte to lock.

To	Separates start from end.

end	Number of the last record or byte to lock.

For Binary mode files, record, start, and end represent the number of a byte relative to the beginning of a file.  The first byte in a file is byte 1.

For Random files, record, start, and end represent the number of a record relative to the beginning of a file.  The first record is record 1.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.

Lock and Unlock statements are always used in pairs.  The arguments to Lock and Unlock must match exactly.

If you specify just one record, then only that record is locked or unlocked.  If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without record locks the entire file; using Unlock without record unlocks the entire file.

If you are using a version of MS-DOS that supports networking (MS-DOS version 3.1 or later), you must run the SHARE.EXE program to enable locking operations.  You can't use Lock and Unlock with earlier versions of MS-DOS.

Note   Be sure to remove all locks with an Unlock statement before closing a file or terminating your program.  Failure to remove locks produces unpredictable results.


See Also

Open Statement


Lock, Unlock Statements Example

The example illustrates the use of the Lock and Unlock statements.  While a record (RecNum) is being updated, access to it on a network is locked to other users until the update is complete.  To try this example, paste the user-defined type declaration into the Declarations section of a module.  Paste the remaining code into the Declarations section of a form.  Then press F5 and click the form.

Type AccountRec	' Define user-defined type.

Payer as String * 20

Address as String * 20

Place as String * 20

Owe as Single

End Type

Sub Form_Click ()

Dim CustRec As AccountRec	' Declare variables

Dim Change, Msg, NL, RecNum

NL = Chr(10)	' Define newline.

On Error GoTo ErrorHandler	' Set up error handler.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Random Shared As #1 Len = Len(CustRec)

Do

RecNum = 1	' Since there is only 1 record,

Lock #1, RecNum 	' lock the current record.

Get #1, RecNum, CustRec	' Read a record.

Msg = "Customer " & CustRec.Payer

Msg = Msg & " currently owes: "

Msg = Msg & Format(CustRec.Owe, "$#,##0.00") & NL & NL

Msg = Msg & "Please input net change (+ or - )"

Change = InputBox(Msg)	' Show data and get change.

If Len(Change) = 0 Then Change = 0

CustRec.Owe = CustRec.Owe + Change

Put #1, RecNum, CustRec	' Update record.

Unlock #1, RecNum	' Unlock the record.

Loop Until Change = 0

Close #1	' Close the file.

Cleanup:

Msg = "Transaction complete. Choose OK to remove the sample "

Msg = Msg & "data file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

Exit Sub

ErrorHandler:

If Err = 70 Then	' Permission denied error.

Msg = "You must run SHARE.EXE before running this example. Exit "

Msg = Msg & "Visual Basic, Exit Windows, run SHARE.EXE, and "

Msg = Msg & "reenter Visual Basic to run this example. Do not "

Msg = Msg & "shell to DOS and run SHARE.EXE or you may not be "

Msg = Msg & "able to run other programs until you reboot."

Else	' Some other error occurred.

Msg = "Error " & Err & " occurred."

End If

MsgBox Msg	' Display error message.

Reset	' Close files, flush buffers.

Resume Cleanup	' Do an orderly exit.

End Sub

Sub MakeDataFile ()

Dim CustRec As AccountRec	' Declare variables.

Open "TESTFILE" For Random Shared As #1 Len = Len(CustRec)

CustRec.Payer = "John Smith"	' Put information in

CustRec.Address = "1 Maple Street" 	' each field of the record.

CustRec.Place = "New York, NY"

CustRec.Owe = 12!	' Initialize owed amount.

Put #1, 1, CustRec	' Put record in file.

Close #1	' Close the file.

End Sub


LOF Function

See Also	Example

Returns the size of an open file in bytes.

Syntax

LOF(filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.

LOF can be used only on disk files.

To obtain the length of a file that is not open, use the FileLen function.


See Also

EOF Function

FileLen Function

Loc Function

Open Statement


LOF Function Example

The example uses LOF to determine the size of an open disk file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open file just created.

FileLength = LOF(1)	' Get length of file.

Close #1	' Close file.

Msg = "The length of the TESTFILE file just created is "

Msg = Msg & FileLength & " bytes." & NL & NL

Msg = Msg & "Choose OK to remove the sample data file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Delete file from disk.

End Sub

Sub MakeDataFile ()

Dim I	' Declare variable.

Open "TESTFILE" For Output As #1	' Open file for output.

For I = 0 To 200	' Generate random values.

Print #1, Int(501 * Rnd)

Next I

Close #1	' Close file.

End Sub


Open Statement

See Also	Example

Enables input/output (I/O) to a file.

Syntax

Open file [For mode] [Access access] [lock] As [#]filenumber [Len = reclen]

Remarks

You must open a file before any I/O operation can be performed on it.  Open allocates a buffer for I/O to the file and determines the mode of access used with the buffer.

The Open statement has these parts:

Part	Description

file	File name or path.

mode	Reserved word that specifies the file mode:  Append, Binary, Input, Output, Random.

access	Reserved word that specifies which operations are permitted on the open file:  Read, Write, Read Write.

lock	Reserved word that specifies which operations are permitted on the open file by other processes: Shared, Lock Read, Lock Write, Lock Read Write.

filenumber	Integer expression with a value between 1 and 255, inclusive.  When an Open statement is executed, filenumber is associated with the file as long as it is open.  Other I/O statements can use the number to refer to the file.

reclen	For files opened for random access, the record length; for sequential files, the number of characters buffered.  The argument reclen is a positive integer expression less than or equal to 32,767 bytes.

If file doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

The argument mode is a reserved word that specifies one of the following file modes.

Mode	Description

Random	Random-access file mode (default).  In this mode, if no Access clause is present, three attempts are made to open the file when the Open statement is executed.  Access is attempted in the following order:

1st.	Read and write
2nd.	Write only
3rd.	Read only

Binary	Binary file mode.  In Binary mode, you can read and write information to any byte position in the file using Get and Put statements.  If no Access clause is present, three attempts are made to open the file, following the same order as for Random files.

Input	Sequential input mode.

Output	Sequential output mode.

Append	Sequential output mode.  Append sets the file pointer to the end of the file.  A Print # or Write # statement then extends (appends to) the file.

If the argument mode is omitted, the default mode (Random) is used.

The argument access is a reserved word that specifies the operations that can be performed on the opened file.  If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and a Permission denied error occurs.

The Access clause works only if you are using a version of MS-DOS that supports networking (MS-DOS version 3.1 or later). You (or the network startup program) must also run the SHARE.EXE program to enable locking operations.  If you use the Access clause with a version of MS-DOS that doesn't support networking, a Feature unavailable error occurs.

The argument access can be one of the following reserved words.

Access type	Description

Read	Opens the file for reading only.

Write	Opens the file for writing only.

Read Write	Opens the file for both reading and writing.  This mode is valid only for Random and Binary files and files opened for Append mode.

The lock clause works in a multiuser or multiprocessing environment to restrict access by other processes or users to an open file.  The argument can be one of the following reserved words.

Lock type	Description

Shared	Any process on any machine can read from or write to this file.

Lock Read	No other process is granted read access to this file.  This lock is applied only if no other process has a previous read access to the file.

Lock Write	No other process is granted write access to this file.  This lock is applied only if no other process has a previous write access to the file.

Lock Read Write	No other process is granted either read or write access to this file.  This access is granted only if read or write access has not already been granted to another process, or if a Lock Read or Lock Write is not already in place.

If you don't specify a lock type, the file can be opened for reading and writing any number of times by the statement, but other operations are denied access to the file while it is open.

When Open is restricted by a previous process, a Permission denied error occurs.

The argument reclen is an integer expression less than or equal to 32,767 bytes.  It specifies settings for Random and sequential files.

For Random files, the argument reclen sets the record length (the number of characters in a record).  The default record length is 128 bytes.

For sequential files, the argument reclen specifies the number of characters to be loaded into the buffer before the buffer is written to or read from the disk.  A larger buffer uses more memory but provides faster file I/O.  Conversely, a smaller buffer leaves more room in memory but slows I/O.  The default buffer size is 512 bytes.

The Len clause and reclen are ignored if mode is Binary.  For sequential files, reclen need not correspond to an individual record size, because a sequential file may have records of different sizes.

Note	In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file.  In Append and Output modes, you must close a file before opening it with a different file number.


See Also

Close Statement

FreeFile Function


Open Statement Example

This example uses Open to open a file for output.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FName, FNum, I, Msg, TestString	' Declare variables.

TestString = "The quick brown fox"	' Create test string.

For I = 1 To 5

FNum = FreeFile	' Determine file number.

FName = "TEST" & FNum & ".DAT"

Open FName For Output As FNum	' Open file.

Print #I, TestString	' Write string to file.

Next I

Close	' Close all files.

Msg = "Several test files have been created on your disk. "

Msg = Msg & "Choose OK to remove the test files."

MsgBox Msg

Kill "TEST?.DAT"	' Remove test files.

End Sub


Print # Statement

See Also	Example

Writes data to a sequential file.

Syntax

Print # filenumber, [ [{Spc(n) | Tab(n)}][ expressionlist] [{; | ,}] ]

Remarks

The Print # statement has these parts:

Part	Description

filenumber	Number used in an Open statement to open a sequential file.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is not optional.

Spc(n)	Name of the Basic function optionally used to insert n spaces into the printed output.  Multiple use is permitted.

Tab(n)	Name of the Basic function optionally used to tab to the nth column before printing expressionlist.  Multiple use is permitted.

expressionlist	Numeric and/or string expressions to be written to the file.

{;|,}	Character that determines the position of the next character printed. A semicolon means the next character is printed immediately after the last character; a comma means the next character is printed at the start of the next print zone.  Print zones begin every 14 columns.  If neither character is specified, the next character is printed on the next line.

If you omit expressionlist, the Print # statement prints a blank line in the file, but you must include the comma.

Because Print # writes an image of the data to the file, you must delimit the data so it is printed correctly.  If you use commas as delimiters, Print # also writes the blanks between print fields to the file.

Also, remember that spacing of data  displayed on a text screen using monospaced characters may not work well when the data is redisplayed in a graphical environment using proportionally spaced characters.

The Print # statement usually writes Variant data to a file the same way it writes any other Visual Basic data type. However, there are some exceptions:

If the data being written is a Variant of VarType 0 (Empty), Print # writes nothing to the file for that data item.

If the data being written is a Variant of VarType 1 (Null), Print # writes the literal #NULL# to the file.

If the data being written is a Variant of VarType 7 (Date), Print # writes the date to the file using the Short Date format defined in the WIN.INI file.  When either the date or the time component is missing or zero, Print # writes only the part provided to the file.


See Also

Open Statement

Print Method

Spc Function

Tab Function

Write # Statement


Print # Statement Example

The example uses the Print # statement to write data to a test file.  Note the use of the comma and semicolon.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileData, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Open "TESTFILE" For Output As #1	' Open to write file.

Print #1, "This is a test of the Print # statement."

Print #1,	' Print blank line to file.

Print #1, "Zone 1", "Zone 2"	' Print in two print zones.

Print #1, "With no space between" ; "."	' Print two strings together.

Close #1	' Close file.

Open "TESTFILE" for Input As #1	' Open to read file.

Do While Not EOF(1)

Line Input #1, FileData	' Read a line of data.

Msg = Msg & FileData & NL	' Construct message.

Loop

Close #1	' Close file.

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Put Statement

See Also	Example

Writes from a variable to a disk file.

Syntax

Put [#] filenumber, [recordnumber], variablename

Remarks

The Put statement has these parts:

Part	Description

filenumber	Number used in an Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

recordnumber	The largest possible recordnumber is 2^31 - 1, or 2,147,483,647.  For files opened in Random mode (with the Random reserved word), recordnumber is the number of the record to be written.  For files opened in Binary mode (with the Binary reserved word), recordnumber is the byte position at which writing starts.  The first byte in a file is at position 1, the second byte is at position 2, and so on.  If you omit recordnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is written.  And if you omit recordnumber, you must still include the delimiting commas.  For example:

Put #4,, FileBuffer

variablename	Name of the variable to write to the file.  Any variable can be used except object variables and array variables (variables that describe an entire array).  However, you can use a variable that describes a single element of an array.

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

If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put still writes subsequent records on record-length boundaries.  The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer.  Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have record length match the length of the data being written.

If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing string length and then the variable.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

If the variable being written is a numeric Variant (VarType 0-7), Put writes 2 bytes identifying the VarType of the Variant and then the variable.  For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data.  The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

If the variable being written is a String Variant (VarType 8), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then the string data.  The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.

If the variable being written is any other type of variable (not a variable-length string and not a Variant), Put writes only the variable data.  The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.

Elements of user-defined types are written using Put as if each were written individually except that there is no padding between elements.  The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements.

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

In Binary mode, the Len clause in the Open statement has no effect.  Put writes all variables to disk contiguously, that is, with no padding between records.

Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor.  The number of bytes written equals the number of characters in the string.  For example, the following statements write 10 bytes to file number 1:

VarString$ = String$(10," ")
Put #1,,VarString$


See Also

Get Statement

Open Statement


Put Statement Example

The example uses Put to write data to a disk file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim ClientName As String * 20	' Declare variables.

Dim Indx, Max, Msg, NL

NL = Chr(10)	' Define newline.

' Make a sample random-access file using the Put statement.

Msg = "Enter a name, using whatever form you like." & NL & NL

Msg = Msg & "Press 'Enter' with no name to conclude entry."

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

ClientName = InputBox(Msg)	' Get user input.

Do While ClientName <> String(20, " ")

Put #1, , ClientName	' Write to file.

ClientName = InputBox(Msg)	' Get user input.

Loop

' Read the sample random-access file using the Get statement.

Max = Loc(1)

If Max = 0 Then	' Check if records exist.

Msg = "Your file contains no names." & NL

Else

Msg = "Your file contains the following names:" & NL & NL

End If

For Indx = 1 To Max

Get #1, Indx, ClientName	' Read from file.

Msg = Msg & ClientName & NL

Next Indx

Close #1	' Close file.

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Reset Statement

See Also	Example

Closes all disk files.

Syntax

Reset

Remarks

The Reset statement closes all open disk files and writes the contents of all MS-DOS file buffers to disk.  .


See Also

Close Statement

End Statement


Reset Statement Example

The example uses Reset to close open files and flush the contents of MS-DOS file buffers out to disk.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim ClientName As String * 20	' Declare variables.

Dim Indx, Max, Msg, NL

NL = Chr(10)	' Define newline.

' Make a sample random-access file using the Put statement.

Msg = "Enter a name, using whatever form you like." & NL & NL

Msg = Msg & "Press 'Enter' with no name to conclude entry."

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

ClientName = InputBox(Msg)	' Get user input.

Do While ClientName <> String(20, " ")

Put #1, , ClientName	' Write to file.

ClientName = InputBox(Msg)	' Get user input.

Loop

Reset	' Flush buffers, close file.

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

' Read the sample random-access file using the Get statement.

Max = Loc(1)

If Max = 0 Then	' Check if records exist.

Msg = "Your file contains no names." & NL

Else

Msg = "Your file contains the following names:" & NL & NL

End If

For Indx = 1 To Max

Get #1, Indx, ClientName	' Read from file.

Msg = Msg & ClientName & NL

Next Indx

Close #1	' Close file.

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Seek Function

See Also	Example

Returns the current file position.

Syntax

Seek (filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.

Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31-1), inclusive.  For files open in Random mode, Seek returns the number of the next record read or written.  For files opened in Binary, Output, Append, or Input mode, Seek returns the byte position at which the next operation is to take place.  The first byte in a file is at position 1, the second byte is at position 2, and so on.


See Also

Get Statement

Open Statement

Put Statement

Seek Statement


Seek Function Example

The example uses the Seek statement to set the file position, and the Seek function to return the current file position.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NameField As String * 20	' Declare form variable.

Dim I, Max, Msg	' Declare variables.

' Create sample data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

' Get user input to fill records.

For I = 1 To 3

NameField = InputBox("Enter student name: ")

Put #1, I, NameField	' Put record on disk.

Next I

Close #1	' Close data file.

' Open data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

Max = LOF(1) \ Len(NameField)	' Calculate # of records.

For I = Max To 1 Step -1	' Read file backwards.

Seek #1, I	' Set file position.

Get #1, , NameField	' Get record.

Msg = "Record #" & (Seek(1) - 1) & " contains: "

Msg = Msg & NameField

MsgBox Msg	' Display student name.

Next I

Close #1	' Close file.

Msg = "Choose OK to remove the test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Seek Statement

See Also	Example

Sets the position in a file for the next read or write.

Syntax

Seek [#]filenumber, position

Remarks

The Seek statement has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

position	Numeric expression that indicates where the next read or write should occur.  The value of position must be between 1 and 2,147,483,647 (equivalent to 2^31-1), inclusive.

For files opened in Random mode, position is the number of a record in the file.

For files opened in Binary, Input, Output, or Append mode, position is the byte position relative to the beginning of the file.  The first byte in a file is at position 1, the second byte is at position 2, and so on.  After a Seek operation, the next file input/output operation starts at the specified byte.

Note	Record numbers in Get and Put statements override file positioning done by Seek.

Performing a file write after doing a Seek operation beyond the end of a file extends the file.  If you attempt a Seek operation to a negative or zero position, an error occurs.


See Also

Get Statement

Open Statement

Put Statement

Seek Function


Seek Statement Example

The example uses the Seek statement to set the file position, and the Seek function to return the current file position.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NameField As String * 20	' Declare form variable.

Dim I, Max, Msg	' Declare variables.

' Create sample data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

' Get user input to fill records.

For I = 1 To 3

NameField = InputBox("Enter student name: ")

Put #1, I, NameField	' Put record on disk.

Next I

Close #1	' Close data file.

' Open data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

Max = LOF(1) \ Len(NameField)	' Calculate # of records.

For I = Max To 1 Step -1	' Read file backwards.

Seek #1, I	' Set file position.

Get #1, , NameField	' Get record.

Msg = "Record #" & (Seek(1) - 1) & " contains: "

Msg = Msg & NameField

MsgBox Msg	' Display student name.

Next I

Close #1	' Close file.

Msg = "Choose OK to remove the test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Spc Function

See Also	Example

Skips a specified number of spaces in a Print # statement or Print method.

Syntax

Spc(number)

Remarks

This function can be used only with the Print # statement or the Print method.

The argument number is an integer between 0 and 32,767, inclusive, that determines the number of blank characters to print.

Note that the Spc function does more than move to a new print position.  The number argument specifies how many blank or space characters are printed starting at the current print position.  When you use Spc on a line with other arguments to either the Print # statement or the Print method and you place no separator (a semicolon or comma) after it, a semicolon (;) is assumed except when Spc appears at the end of a line. For example, Print #1, Spc(10) FixLen1$ and Print#1, Spc(10); FixLen1$ are equivalent.

When used with files, Spc behaves in the following way:

If number is less than the output line width, the next print position immediately follows the number of spaces printed.

If number is greater than the output-line width, Spc calculates printposition =  number Mod width and generates the number of spaces indicated by that calculation, starting at the current print position.

If the difference between the current print position and the output-line width is less than number (or number Mod width), the Spc function skips to the beginning of the next line and generates a number of spaces equal to number - (width - currentprintposition).

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font.  However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.  Make sure your tabular columns are wide enough to accommodate wider letters.


See Also

Print Method

Print # Statement

Space, Space$ Function

Tab Function

Width # Statement


Spc Function Example

The example uses the Spc function to embed 10 spaces in an output file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

Open "TESTFILE" For Output As #1	' Create sample data file.

Print #1, "This is a test of the "; Spc(10); "Spc function."

Close #1	' Close file.

Open "TESTFILE" For Input As #1	' Reopen the file for input.

Input #1, Msg	' Read the data.

Close #1	' Close file.

MsgBox Msg	' Display file contents.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Tab Function

See Also	Example

Used with the Print # statement and the Print method to move the position at which the next character is printed.

Syntax

Tab(column)

Remarks

This function can be used only with the Print # statement or the Print method.

The argument column is an integer expression that is the column number of the new print position.

The leftmost print position on an output line is always 1.  When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

When you use Tab on a line with other arguments to either the Print # statement or the Print method and you place no separator (a semicolon or comma) after it, a semicolon (;) is assumed except when Tab appears at the end of a line.

When used with forms and files, Tab behaves in the following way:

If the current print position on the current line is greater than column, Tab skips to column on the next output line.

If column is less than 1, Tab moves the print position to column 1.

When used with files only, Tab displays the following behavior:

If column is greater than the output-line width, Tab calculates
printposition = column Mod width

If the column is less than the current print position, printing begins on the next line at the calculated print position.  If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns.  The width of each column is an average of the width of all characters in the point size for the chosen font.  However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, the uppercase letter W occupies more than one fixed-width column and the lowercase letter I occupies less.  Make sure your tabular columns are wide enough to accommodate wider letters.


See Also

Print # Statement

Space, Space$ Function

Spc Function

Width # Statement


Tab Function Example

The example uses the Tab function to move the print position to column 40 in an output data file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

Open "TESTFILE" For Output As #1	' Create sample data file.

Print #1, "This is a test of the "; Tab(40); "Tab function."

Close #1	' Close file.

Open "TESTFILE" For Input As #1	' Reopen the file for input.

Input #1, Msg	' Read the data.

Close #1	' Close file.

MsgBox Msg	' Display file contents.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Width Statement

See Also	Example

Assigns an output-line width to a file.

Syntax

Width # filenumber, width

Remarks

The Width # statement has these parts:

Part	Description

filenumber	Number used to open the file with the Open statement.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is not optional.

width	Numeric expression in the range 0 to 255, inclusive, that indicates how many characters appear on a line before a new line is started.  If width equals 0, there is no limit to the length of a line.  The default value for line width is 0.

The Width # statement permits output-line width to be changed in files that are already open.


See Also

Open Statement

Print # Statement


Width Statement Example

The example uses the Width statement to set the output-line width for a file.  A test file is created, and the same characters are written to two different line widths.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL, Text	' Declare variables.

NL = Chr(10)	' Define newline.

Open "TESTFILE" For Output As #1	' Create sample data file.

For I = 0 To 9	' Print ASCII characters

Print #1, Chr(48 + I);	' 0-9 to test file

Next I	' all on same line.

Print #1,	' Start new line.

Width #1, 5	' Change line width to 5.

For I = 0 To 9	' Print 0-9 again. This

Print #1, Chr(48 + I);	' time, five characters print

Next I	' before line wraps.

Close #1	' Close file.

Msg = "The effect of the Width statement is as shown below: " & NL

Open "TESTFILE" For Input As #1	' Reopen the file for input.

Do While Not Eof(1)

Input #1, Text	' Get lines from file.

Msg = Msg & NL & Text	' Create message.

Loop

Close #1	' Close file.

Msg = Msg & NL & NL & "Choose OK to remove the test file."

MsgBox Msg	' Display effects of Width.

Kill "TESTFILE"	' Remove test file from disk.

End Sub


Write# Statement

See Also	Example

Writes data to a sequential file.

Syntax

Write # filenumber [, expressionlist]

Remarks

The Write # statement has these parts:

Part	Description

filenumber	Number used in an Open statement to open a sequential file.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is required.

expressionlist	Comma-delimited numeric and/or string expressions to be written to the file.  If you omit expressionlist, the Write # statement writes a blank line to the file.

The file identified by filenumber must be opened in Output or Append mode.

Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file.  You don't have to put explicit delimiters in the list.  Write # inserts a newline character after it has written the final character in expressionlist to the file.

Usually, the Write # statement writes Variant data to a file in the same way it writes any other Visual Basic data type. However, there are some exceptions:

If the data being written is a Variant of VarType 0 (Empty), Write # writes nothing to the file for that data item.  However, if multiple items are written to the file, the delimiting commas themselves are written to the file.

If the data being written is a Variant of VarType 1 (Null), Write # writes the literal #NULL# to the file.

If the data being written is a Variant of VarType 7 (Date), Write # writes the date to the file using the fixed date format #yyyy-mm-dd hh:mm:ss#.  When either the date or the time component is missing or zero, Write # writes only the part provided to the file.


See Also

Open Statement

Print # Statement


Write # Statement Example

The example uses Write # to write two variables to a sequential file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, UsrAge, UsrName	' Declare variables.

NL = Chr(10)	' Define newline.

' Make a sample data file.

Open "TESTFILE" For Output As 1	' Open file for output.

Msg = "Enter your name."

UsrName = InputBox(Msg)	' Get user name.

Msg = "Enter your age."

UsrAge = InputBox(Msg)	' Get user age.

Write #1, UsrName, UsrAge	' Write data to file.

Close #1	' Close file.

' Read the sample data file

Open "TESTFILE" For Input As #1	' Open file for input.

Input #1, UsrName, UsrAge	' Read data.

Close #1	' Close file.

Msg = "The name '" & UsrName & "' was read from the data file. "

Msg = Msg & "'" & UsrAge & "' is the age you gave."

Msg = Msg & NL & NL & "Choose OK to remove test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Circle Method

See Also	Example

Draws a circle, ellipse, or arc on an  object.

Syntax

[object.]Circle [Step](x, y), radius[,[color] [,[start] [,[end] [,aspect] ] ] ]

Remarks

The Circle method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) on which the circle is drawn.

Step	Specifies that the center of the circle, ellipse, or arc is relative to the current coordinates, given by the CurrentX and CurrentY properties of object.

(x,y)	Single-precision values indicating the coordinates for the center point of the circle, ellipse, or arc.  The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the units of measure used.

radius	Single-precision value indicating the radius of the circle, ellipse, or arc.  The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used.

color	Long integer value indicating the RGB color of the circle's outline.  If omitted, the value of the ForeColor property is used.  You can use the RGB function or QBColor function to specify the color.

start, end	Single-precision values.  When a partial circle or ellipse is  drawn, start and end specify (in radians) the beginning and end positions of the arc.  The range for both is -2 Pi radians to 2 Pi radians.  The default value for start is 0 radians; the default for end is 2 * Pi radians.

aspect	Single-precision value indicating the aspect ratio of the circle .  The default value is 1.0, which yields a perfect (non-elliptical) circle on any screen.

To fill a circle, set the FillColor and FillStyle properties of the object where the circle or ellipse is drawn.  Only a closed figure can be filled.  Closed figures include circles, ellipses, or pie slices (arcs with radius lines drawn at both ends).

When drawing a partial circle or ellipse, if start is negative, Circle draws a radius to start, and treats the angle as positive; if end is negative, Circle draws a radius to end and treats the angle as positive.  The Circle method always draws in a counter-clockwise (positive) direction.

The width of the line used to draw the circle, ellipse, or arc depends on the DrawWidth property.  The way the circle is drawn on the background depends on the setting of the DrawMode and DrawStyle properties.

When drawing pie slices, if you need to draw a radius to angle 0 (giving a horizontal line segment to the right), specify a very small negative value for start, rather than zero.

You can omit an argument in the middle of the syntax, but you must include the argument's comma before including the next argument.  If you omit a trailing argument, don't use any commas following the last argument you specify.

When Circle executes, CurrentX and CurrentY are set to the center point specified by the arguments.


See Also

BackColor, ForeColor Properties

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

QBColor Function

RGB Function

ScaleMode Property

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

Shape Control


Circle Method Example

The Circle method draws a number of concentric circles in the center of a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, Radius	' Declare variable.

ScaleMode = 3	' Set scale to pixels.

CX = ScaleWidth / 2	' Set X position.

CY = ScaleHeight / 2	' Set Y position.

If CX > CY Then Limit = CY Else Limit = CX

For Radius = 0 to Limit	' Set radius.

Circle (CX, CY), Radius,RGB(Rnd * 255, Rnd * 255, Rnd * 255)

Next Radius

End Sub


EndDoc Method

See Also	Example

Terminates a document sent to the Printer, releasing it to the print device or spooler.

Syntax

Printer.EndDoc

Remarks

If EndDoc is invoked immediately after NewPage, no additional blank page is printed.


See Also

NewPage Method

Printer Object


EndDoc Method Example

The example uses the EndDoc method to end a document after printing two pages, each with a centered line of text indicating the page number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HWidth, HHeight, I, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This is printed on page"

For I = 1 To 2	' Set up two iterations.

HWidth = Printer.TextWidth(Msg) / 2	' Get half width.

HHeight = Printer.TextHeight(Msg) /2	' Get half height.

Printer.CurrentX = Printer.ScaleWidth / 2 - HWidth

Printer.CurrentY = Printer.ScaleHeight / 2 - HHeight

Printer.Print Msg & Printer.Page & "."	' Print.

Printer.NewPage	' Send new page.

Next I

Printer.EndDoc	' Print done.

Msg = "Two pages, each with a single, centered line of text, "

Msg = Msg & "have been sent to your printer."

MsgBox Msg	' Display message.

Exit Sub

ErrorHandler:

MsgBox "There was a problem printing to your printer."

Exit Sub

End Sub


Line Method

See Also	Example

Draws lines and rectangles on an object.

Syntax

[object.]Line [[Step](x1, y1)] - [Step](x2, y2) [,[color][,B[F]]]

Remarks

The Line method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) on which the line or rectangle is to be drawn.

Step	Keyword that specifies that the starting point coordinates are relative to the current graphics position, given by the CurrentX and CurrentY properties.

x1, y1	Single-precision values indicating the coordinates of the starting point for the line or rectangle.  The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used.  If omitted, the line begins at the position indicated by CurrentX and CurrentY.

Step	Keyword that specifies that the end point coordinates are relative to the line starting point.

x2, y2	Single-precision values indicating the coordinates of the end point for the line to draw.  These coordinates are required.

color	Long integer value indicating the RGB color used to draw the line.  If omitted, the ForeColor property is used.  You can use the RGB function or QBColor function to specify the color.

B	Option that causes a box to be drawn using the coordinates to specify opposite corners of the box.

F	If the B option is used, the F option specifies that the box is filled with the same color used to draw the box.  You cannot use F without B.  If B is used without F, the box is filled with the current FillColor and FillStyle.  The default value for FillStyle is transparent.

When drawing lines that are connected, lines should be drawn so that subsequent lines begin at the end point of the previous line.

The width of the line drawn depends on the DrawWidth property.  The way a line or box is drawn on the background depends on the setting of the DrawMode and DrawStyle properties.

When Line executes, CurrentX and CurrentY are set to the end point specified by the arguments.


See Also

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

ForeColor Property

Line Control

QBColor Function

RGBFunction

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property

Shape Control


Line Method Example

The Line method example draws concentric boxes on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, F, F1, F2, I	' Declare variables

ScaleMode = 3	' Set ScaleMode to pixels.

CX = ScaleWidth / 2	' Get horizontal center.

CY = ScaleHeight / 2	' Get vertical center.

DrawWidth = 8	' Set DrawWidth.

For I = 50 To 0 Step -2

F = I / 50	' Perform interim

F1 = 1 - F: F2 = 1 + F	' calculations.

Forecolor = QBColor(I Mod 15)	' Set foreground color.

Line (CX * F1, CY * F1)-(CX * F2, CY * F2), , BF

Next I

DoEvents	' Yield for other processing.

If CY > CX Then	' Set DrawWidth.

DrawWidth = ScaleWidth / 25

Else

DrawWidth = ScaleHeight / 25

End If

For I = 0 To 50 Step 2	' Set up loop.

F = I / 50	' Perform interim

F1 = 1 - F: F2 = 1 + F	' calculations.

Line (CX * F1, CY)-(CX, CY * F1)	' Draw upper-left.

Line -(CX * F2, CY)	' Draw upper-right.

Line -(CX, CY * F2)	' Draw lower-right.

Line -(CX * F1, CY)	' Draw lower-left.

Forecolor = QBColor(I Mod 15)	' Change color each time.

Next I

DoEvents	' Yield for other processing.

End Sub


NewPage Method

See Also	Example

Ends the current page and advances to the next.

Syntax

Printer.Newpage

Remarks

The NewPage method advances to the next printer page and resets the print position to the upper-left corner of the new page.

When invoked, NewPage increments the Printer object's Page property by 1.


See Also

EndDoc Method

Page Property

Printer Object


NewPage Method Example

The example uses the NewPage method to begin a new printer page after printing a single, centered line of text on a page.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HWidth, HHeight, I, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This is printed on page"

For I = 1 To 2	' Set up two iterations.

HWidth = Printer.TextWidth(Msg) / 2	' Get half width.

HHeight = Printer.TextHeight(Msg) /2	' Get half height.

Printer.CurrentX = Printer.ScaleWidth / 2 - HWidth

Printer.CurrentY = Printer.ScaleHeight / 2 - HHeight

Printer.Print Msg & Printer.Page & "."	' Print.

Printer.NewPage	' Send new page.

Next I

Printer.EndDoc	' Print done.

Msg = "Two pages, each with a single, centered line of text, "

Msg = Msg & "have been sent to your printer."

MsgBox Msg	' Display message.

Exit Sub

ErrorHandler:

MsgBox "There was a problem printing to your printer."

Exit Sub

End Sub


Point Method

See Also	Example

Returns the RGB color of the specified point on a form or picture box.

Syntax

[object.]Point(x,y)

Remarks

The Point method has these parts:

Part	Description

object	Object (non-MDI form or picture box) where the specified point is located.

x	Single-precision value indicating the horizontal (x-axis) coordinate of the point, in the scale mode of the form or picture box.

y	Single-precision value indicating the vertical (y-axis) coordinate of the point, in the scale mode of the form or picture box.

If the point referred to by the x and y coordinates is outside the object, the Point method returns -1.


See Also

Circle Method

Line Method

Print Method

PSet Method


Point Method Example

The example uses the Point method to determine the color of a specific point on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim LeftColor, MidColor, Msg, RightColor	' Declare variables.

AutoRedraw = -1	' Turn on AutoRedraw.

Height = 3 * 1440	' Set height to 3 inches.

Width = 5 * 1440	' Set width to 5 inches.

Backcolor = QBColor(1)	' Set background to blue.

Forecolor = QBColor(4)	' Set foreground to red.

Line (0, 0)-(Width / 3, Height), , BF	' Red box.

Forecolor = QBColor(15)	' Set foreground to white.

Line (Width / 3, 0)-((Width / 3) * 2, Height), , BF

LeftColor = Point(0, 0)	' Find color of left box,

MidColor = Point(Width / 2, Height / 2)	' Middle box, and

RightColor = Point(Width, Height)	' Right box.

Msg = "The color number for the red box on the left side of "

Msg = Msg & "the form is " & LeftColor & ". The "

Msg = Msg & "color of the white box in the center is "

Msg = Msg & MidColor & ". The color of the blue "

Msg = Msg & "box on the right is " & RightColor & "."

MsgBox Msg	' Display message.

End Sub


Print Method

See Also	Example

Prints a text string on an object using the current color and font.

Syntax

[object.]Print [{Spc(n) | Tab(n)}][expressionlist][{; | ,}]

Remarks

The Print method has these parts:

Part	Description

object	Object (non-MDI form, picture box, Debug, or Printer object) on which expressionlist is to be printed.

Spc(n)	Name of the Basic function optionally used to insert n spaces into the printed output.  Multiple use is permitted.

Tab(n)	Name of the Basic function optionally used to tab to the nth column before printing expressionlist.  Multiple use is permitted.

expressionlist	Numeric or string expressions to print.  If omitted, Print prints a blank line. Multiple expressions can be separated with a space, a semicolon , or a comma.  A space has the same effect as a semicolon.  Spc and Tab can also be used with each separate expression.

{;|,}	Character that determines the location of the text cursor for the next character displayed: a semicolon means the cursor is placed immediately after the last character displayed; a comma means the cursor is placed at the start of the next print zone.  Print zones begin every 14 columns.  If neither character is specified, the next character is printed on the next line.  The width of each column is an average of the width of all characters in the point size for the chosen font.

The expressionlist is printed on the object starting at the position indicated by CurrentX and CurrentY properties.

Normally, when expressionlist is printed, a carriage return is appended so that the next Print begins printing on the next line.  When a carriage return occurs, CurrentY is increased by the height of expressionlist (same as the value returned by TextHeight) and the CurrentX is set to zero.

When a semicolon follows the expressionlist, no carriage return is appended, and the next Print displays on the same line as the current Print.  The CurrentX and CurrentY are set to the point immediately after the last character printed.  If the expressionlist itself contains carriage returns, each such embedded carriage return sets CurrentX and CurrentY as described above for Print without a semicolon.

When a comma follows expressionlist, CurrentX and CurrentY are set to the next print zone on the same line.

There is no scrolling of lines that cannot fit in the specified position.  The printed string is clipped to fit the object on which it is displayed.

Because the Print method normally prints with proportionally-spaced characters, it is important to remember that there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy.  For example, a wide letter, such as a "W", occupies more than one fixed-width column, whereas a narrow letter, such as an "i", occupies less.  To account for cases where wider than average characters are used, you must ensure that your tabular columns are positioned far enough apart.  Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column.


See Also

CurrentX, CurrentY Properties

Printer Object

NewPage Method

PrintForm Method

Spc Function

Tab Function

TextHeight Method


Print Method Example

The example uses the Print method to display some text on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, I, J, K, L, M, Msg, Offset	' Declare variables.

Cls	' Clear form.

Width = 7200	' Set form width.

Height = 5000	' Set form height.

BackColor = QBColor(1)	' Set background color.

For I = 1 To 3

Select Case I

Case 1	' First time.

ForeColor = QBColor(5)	' Set foreground color.

K = 1: L = 9: M = 1

Msg = "Visual"	' Set message.

CX = 0	' Set position variable.

Case 2	' Second time.

K = 1: L = 9: M = 1

Msg = "Basic"

CX = ScaleWidth

Case 3	' Third time.

ForeColor = QBColor(15)

K = 9: L = 1: M = -1

Msg = "Visual Basic"

CX = ScaleWidth / 2

End Select

For J = K To L Step M

Select Case J	' Change font size.

Case 1: Fontsize = 8

Case 2: Fontsize = 10

Case 3: Fontsize = 12

Case 4: Fontsize = 14

Case 5: Fontsize = 18

Case 6: Fontsize = 20

Case 7: Fontsize = 24

Case 8: Fontsize = 36

Case 9: Fontsize = 48

End Select

If I = 1 Then

Offset = 0	' Text on left.

ElseIf I = 2 Then

Offset = TextWidth(Msg)	' Text on right.

Else

Offset = TextWidth(Msg) / 2	' Text in center.

End If

CurrentX = CX - Offset

Print Msg	' Print message.

Next J

CurrentY = 0	' Reset to top of form.

Next I

End Sub


PrintForm Method

See Also	Example

Sends a bit-for-bit image of a non-MDI form to the printer.

Syntax

[form.]PrintForm

Remarks

The argument form is the non-MDI form to print.  If omitted, the current form is printed.  PrintForm prints all visible controls and bitmaps on the form.  PrintForm also prints graphics added to the form or picture controls on the form at run time if AutoRedraw is True when the graphics are drawn.

The printer used by PrintForm is determined by the Microsoft Windows control panel.


See Also

AutoRedraw Property

Print Method

Printer Object


PrintForm Method Example

The example uses the PrintForm method to print the current form.  To try this example, paste the code into the Declarations section of a form.  Place on the form any controls you want to see in the printed form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

On Error GoTo ErrorHandler	' Set up error handler.

PrintForm	' Print form.

Exit Sub

ErrorHandler:

Msg = "The form could not be printed."

MsgBox Msg	' Display message.

Resume Next

End Sub


PSet Method

See Also	Example

Action

Sets a point on an object to a specified color.

Syntax

[object.]PSet [Step](x, y)[,color]

Remarks

The PSet method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) on which point is to be drawn.

Step	Keyword that specifies that the coordinates are relative to the current graphics position given by the CurrentX and CurrentY properties.

x, y	Single-precision values indicating the horizontal and vertical coordinates of the point to set.

color	RGB color specified for point.  If omitted, the current foreground color is used.  You can use the RGB function or QBColor function to specify the color.

The size of the point drawn depends on the DrawWidth property.  When DrawWidth is 1, PSet sets a single pixel to the specified color.  When DrawWidth is greater than 1, the point is centered on the specified coordinates.

The way the point is drawn depends on the setting of the DrawMode and DrawStyle properties.

When PSet executes, CurrentX and CurrentY are set to the point specified by the arguments.

Clear a single pixel with the PSet method by specifying the coordinates of the pixel and using BackColor as the color argument.


See Also

BackColor, ForeColor Properties

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

RGB Function

QBColor Function


PSet Method Example

The PSet method example draws confetti on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, Msg, XPos, YPos	' Declare variables.

ScaleMode = 3	' Set ScaleMode to pixels.

DrawWidth = 5	' Set DrawWidth.

ForeColor = QBColor(4)	' Set background to red.

FontSize = 24	' Set point size.

CX = ScaleWidth / 2	' Get horizontal center.

CY = ScaleHeight / 2	' Get vertical center.

Cls	' Clear form.

Msg = "Happy New Year!"

CurrentX = CX - TextWidth(Msg) / 2	' Horizontal position.

CurrentY = CY - TextHeight(Msg)	' Vertical position.

Print Msg	' Print message.

Do

XPos = Rnd * ScaleWidth	' Get horizontal position.

YPos = Rnd * ScaleHeight	' Get vertical position.

PSet (XPos, YPos), QBColor(Rnd * 15)	' Draw confetti.

DoEvents	' Yield for other processing.

Loop

End Sub


QBColor Function

See Also	Example

Returns the RGB color code corresponding to a color number.

Syntax

QBColor (qbcolor)

Remarks

The qbcolor argument is an integer in the range 0-15, inclusive, that corresponds to the color values used by other versions of Basic (such as Microsoft Visual Basic for MS-DOS and Basic Compiler). Starting with the least-significant byte, the returned value specifies the red, green, and blue values used to set the appropriate color in the RGB system used by Visual Basic.

The following table shows the possible settings for qbcolor:

Number [image] Color	Number [image] Color
0 [image] Black	8 [image] Gray
1 [image] Blue	9 [image] Light Blue
2 [image] Green	10 [image] Light Green
3 [image] Cyan	11 [image] Light Cyan
4 [image] Red	12 [image] Light Red
5 [image] Magenta	13 [image] Light Magenta
6 [image] Yellow	14 [image] Light Yellow
7 [image] White	15 [image] Bright White


See Also

 RGB Function


QBColor Function Example

The example uses the QBColor function to show the range of colors on a form. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable

Cls	' Clear form.

ScaleHeight = 16	' Divide form into 16 parts.

For I = 0 To 15	' Draw a colored box.

Line(0, I)-(ScaleWidth, I + 1), QBColor(I), BF

Next I

End Sub


RGB Function

See Also	Example

Returns a long integer representing an RGB color value.

Syntax

RGB (red, green, blue)

Remarks

The RGB function has these parts:

Part	Description

red	Integer in the range of 0 to 255, inclusive, that represents the red component of the color.

green	Integer in the range of 0 to 255, inclusive, that represents the green component of the color.

blue	Integer in the range of 0 to 255, inclusive, that represents the blue component of the color.

Visual Basic methods and properties that accept a color specification expect that specification to be a long integer representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue, which taken together cause a specific color to be displayed.

If the value for any argument to RGB exceeds 255, it is assumed to be 255.

The following table shows the hexadecimal representation for some standard colors, their corresponding RGB values, and the red, green and blue components for each:

Color	RGB Value	Red Value	Green Value	Blue Value
Black	&H00	0	0	0
Blue	&HFF0000	0	0	255
Green	&HFF00	0	255	0
Cyan	&HFFFF00	0	255	255
Red	&HFF	255	0	0
Magenta	&HFF00FF	255	0	255
Yellow	&HFFFF	255	255	0
White	&HFFFFFF	255	255	255


See Also

QBColor Function


RGB Function Example

The RGB function example displays a variety of color shades on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

Cls	' Clear form

ScaleHeight = 128	' Divide form into 128 parts.

For I = 0 To 126 Step 2	' Draw a colored box.

Line (0, I)-(ScaleWidth, I + 2), RGB(I, 64 + I, 128 + I),BF

Next I

End Sub


Scale Method

See Also	Example

Defines the coordinate system for an object.

Syntax

[object.]Scale [(x1, y1) - (x2, y2)]

Remarks

The Scale method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) to which the coordinate system is applied.

x1, y1	Single-precision values for the horizontal and vertical coordinates that define the upper-left corner of the object.

x2, y2	Single-precision values for the horizontal and vertical coordinates that define the lower-right corner of the object.

The Scale method allows you to reset the coordinate system to any scale you choose. Scale with no arguments resets the coordinate system to twips. Scale affects the coordinate system for the both the run-time graphics statements and the placement of controls.


See Also

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleTop Property

ScaleWidth Property


Scale Method Example

The example uses the Scale method to set up a custom coordinate system so that a bar chart can be drawn on a form. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, OldFontSize	' Declare variables

Width = 8640: Height = 5760	' Set form size in twips.

Move 100,100	' Move form origin.

AutoRedraw = -1	' Turn on AutoRedraw.

OldFontSize = FontSize	' Save old font size.

BackColor = QBColor(7)	' Set background to gray.

Scale (0, 110)-(130, 0)	' Set custom coordinate system.

For I = 100 To 10 Step -10

Line (0, I)-(2, I)	' Draw scale marks every 10 units.

CurrentY = CurrentY + 1.5	' Move cursor position.

Print I	' Print scale mark value on left.

Line (ScaleWidth - 2, I)-(ScaleWidth, I)

CurrentY = CurrentY + 1.5	' Move cursor position.

CurrentX = ScaleWidth - 9

Print I	' Print scale mark value on right.

Next I

' Draw bar chart

Line (10, 0)-(20, 45), RGB(0, 0, 255), BF	' 1st blue bar.

Line (20, 0)-(30, 55), RGB(255, 0, 0), BF	' 1st red bar.

Line (40, 0)-(50, 40), RGB(0, 0, 255), BF

Line (50, 0)-(60, 25), RGB(255, 0, 0), BF

Line (70, 0)-(80, 35), RGB(0, 0, 255), BF

Line (80, 0)-(90, 60), RGB(255, 0, 0), BF

Line (100, 0)-(110, 75), RGB(0, 0, 255), BF

Line (110, 0)-(120, 90), RGB(255, 0, 0), BF

CurrentX = 18: CurrentY = 100	' Move cursor position.

FontSize = 14	' Enlarge font for title.

Print "Widget Quarterly Sales"	' Print title.

FontSize = OldFontSize	' Restore font size.

CurrentX = 27: CurrentY = 93	' Move cursor position.

Print "Planned Vs Actual"	' Print subtitle.

Line (29, 86)-(34, 88), RGB(0, 0, 255), BF	' Print legend.

Line (43, 86)-(49, 88), RGB(255, 0, 0), BF

End Sub


TextHeight Method

See Also	Example

Action

Returns the height of a text string as it would be printed in the current font of an object.

Syntax

[object.]TextHeight(stringexpression)

Remarks

The TextHeight method has these parts:

Part	Description

object	Object (non MDI form, picture box, or Printer object) that determines the font size upon which the text height is based.

stringexpression	Text string for which the text height is determined.

The height is expressed in terms of the Scale coordinate system in effect for object.  Use TextHeight to determine the amount of vertical space required to display the text.  The height returned includes the normal "leading" space above and below the string, so you can use the height to calculate and position multiple lines of text within a form, picture box, or Printer object.  If stringexpression contains embedded carriage returns, TextHeight returns the cumulative height of the lines, including the leading space above and below each line.


See Also

FontSize Property

Scale Method

TextWidth Method


TextHeight Method Example

The TextHeight method is used to center a line vertically on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HalfWidth, HalfHeight, Msg	' Declare variable.

AutoRedraw = -1	' Turn on AutoRedraw.

BackColor = QBColor(4)	' Set background color.

ForeColor = QBColor(15)	' Set foreground color.

Msg = "Visual Basic"	' Create message.

Fontsize = 48	' Set font size.

HalfWidth = TextWidth(Msg) / 2 	' Calculate half width.

HalfHeight = TextHeight(Msg) / 2	' Calculate half height.

CurrentX = ScaleWidth / 2 - HalfWidth	' Set X.

CurrentY = ScaleHeight / 2 - HalfHeight	' Set Y.

Print Msg	' Print message.

End Sub


TextWidth Method

See Also	Example

Action

Returns the width of a text string as it would be printed in the current font of an object.

Syntax

[object.]TextWidth(stringexpression)

Remarks

The TextWidth method has these parts:

Part	Description

object	Object (non MDI form, picture box, or Printer object) that determines the font size upon which the text width is based.

stringexpression	Text string for which the text width is determined.

The width is expressed in terms of the Scale coordinate system of object.  Use TextWidth to determine the amount of horizontal space required to display the text.  If stringexpression contains embedded carriage returns, TextWidth returns the width of the longest line.


See Also

FontSize Property

Scale Method

TextHeight Method


TextWidth Method Example

The TextWidth method is used to center a line of text horizontally on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HalfHeight, HalfWidth, Msg	' Declare variables.

AutoRedraw = -1	' Turn on AutoRedraw.

BackColor = QBColor(4)	' Set background color.

ForeColor = QBColor(15)	' Set foreground color.

Msg = "Visual Basic"	' Create message.

Fontsize = 48	' Set font size.

HalfWidth = TextWidth(Msg) / 2 	' Calculate half width.

HalfHeight = TextHeight(Msg) / 2	' Calculate half height.

CurrentX = ScaleWidth / 2 - HalfWidth	' Set X.

CurrentY = ScaleHeight / 2 - HalfHeight	' Set Y.

Print Msg	' Print message.

End Sub


IsDate Function

See Also	Example

Returns a value indicating whether or not a Variant argument can be converted to a date.

Syntax

IsDate(variant)

Remarks

The argument variant can be any Variant expression of VarType 7 (Date) or of VarType 8 (String).  The IsDate function returns True if the Variant can legally be converted to a date; otherwise, it returns False.  The range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.


See Also

CVDate Function

IsEmpty Function

IsNull Function

IsNumeric Function

VarType Function


IsDate Function Example

The example evaluates TestVar to determine whether it can legally be converted to a numeric data type and displays an appropriate message.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestVar	' Declare variable.

TestVar = InputBox("Enter a string you'd like displayed as a date.")

If IsDate(TestVar) Then	' Test variable.

MsgBox "The date is: " & Format(CVDate(TestVar),"dddddd")

Else

MsgBox "What you entered doesn't make sense as a date."

End If

End Sub


IsEmpty Function

See Also	Example

Returns a value indicating whether or not a Variant variable has been initialized.

Syntax

IsEmpty(variant)

Remarks

The argument variant can be any Variant expression.  However, because IsEmpty is used to determine whether or not variables are initialized, the argument is most often a single variable name.  The IsEmpty function returns True if the Variant contains the Empty value; otherwise, it returns False.  When an expression contains more than one Variant, IsEmpty always returns False.

The Empty value indicates that a Variant has not been initialized.  Empty is not the same as Null, which indicates that a Variant contains no data.


See Also

IsDate Function

IsNull Function

IsNumeric Function

VarType Function


IsEmpty Function Example

The example uses IsEmpty to determine whether TestVar has been initialized.  If it hasn't been initialized, the user is asked if it should be.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim InitVar, TestVar	' Declare variable.

If IsEmpty(TestVar) Then	' Test variable.

InitVar = MsgBox("TestVar is uninitialized. Initialize now?", 36)

If InitVar = 6 Then	' If Yes,

TestVar = 1.25	' initialize TestVar.

MsgBox "TestVar initialized to " & TestVar

End If

End If

End Sub


IsNull Function

See Also	Example

Returns a value that indicates whether or not a Variant contains the special Null value.

Syntax

IsNull(variant)

Remarks

The argument variant can be any Variant expression.  The IsNull function returns True if the expression contains the Null value; otherwise, it returns False.

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

Caution	Using the IsNull function is the only way from within Visual Basic to determine whether or not a Variant expression contains a Null value.  Expressions that you might expect to evaluate True under some circumstances, such as If Var = Null and If Var <> Null, are always False.  This is because any expression containing a Null is itself Null and therefore False.


See Also

IsDate Function

IsEmpty Function

IsNumeric Function

VarType Function


IsNull Function Example

The example evaluates TestVar to determine whether it contains the Null value and then displays an appropriate message.  The variable TestVar starts as Null but is changed to a zero-length string the first time through the loop.  The second time through the loop, TestVar again becomes Null and the loop exits.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestVar	' Declare variable.

TestVar = Null	' Initialize as Null.

Do

If IsNull(TestVar) Then	' Evaluate variable.

MsgBox "TestVar is Null."	' Indicate if Null.

TestVar = "" 	' Make zero-length string.

Else

MsgBox "TestVar is not Null."	' Indicate if not Null.

TestVar = Null	' Make Null.

End If

Loop Until IsNull(TestVar)	' Loop until TestVar is Null.

End Sub


IsNumeric Function

See Also	Example

Returns a value indicating whether or not a Variant variable can be converted to a numeric data type.

Syntax

IsNumeric(variant)

Remarks

The argument variant can be any Variant expression.  The IsNumeric function returns True if the expression can legally be converted to a number; otherwise, it returns False.  Expressions that can legally be converted to a numeric data type include Variant variables of VarType 0 (Empty), of any numeric value (VarType 2-6), of VarType 7 (Date), and of VarType 8 (String) if the String can be interpreted as numeric.


See Also

IsDate Function

IsEmpty Function

IsNull Function

VarType Function


IsNumeric Function Example

The example evaluates TestVar to determine whether it can legally be converted to a numeric data type and displays an appropriate message.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestVar	' Declare variable.

TestVar = InputBox("Please enter a number, letter, or symbol.")

If IsNumeric(TestVar) Then	' Evaluate variable.

MsgBox "Entered data is numeric."	' Message if number.

Else

MsgBox "Entered data is not numeric."	' Message if not.

End If

End Sub


VarType Function

See Also	Example

Returns a value that indicates how a Variant is stored internally by Visual Basic.

Syntax

VarType(variant)

Remarks

The argument variant is a variable of the Variant data type.  The VarType function returns a value that provides information about the type of data stored in the Variant.

The value returned by VarType is one of the following:

Symbolic Constant	Value	Meaning
V_EMPTY	0	Empty
V_NULL	1	Null
V_INTEGER	2	Integer
V_LONG	3	Long
V_SINGLE	4	Single
V_DOUBLE	5	Double
V_CURRENCY	6	Currency
V_DATE	7	Date
V_STRING	8	String
Note	Symbolic constants for file Variant definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Data Types

IsDate Function

IsEmpty Function

IsNull Function

IsNumeric Function


VarType Function Example

The example uses VarType to determine whether a Variant argument passed to the function is either a Single or a Double.  True is returned if the argument is one of these types of data, False if it is not.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Num	' Declare variable.

Num = InputBox("Enter a number.")	' Get number from user.

If IsNumeric(Num) Then

Num = CDbl(Num)

Else

MsgBox "You did not enter a number."

Exit Sub

End If

If IsReal(Num) Then

MsgBox "What you entered is a real number."

Else

MsgBox "What you entered is not a real number."

End If

End Sub

Function IsReal(VarArg)

If VarType(VarArg) = 4 Or VarType(VarArg) = 5 Then

IsReal = True	' If Single or Double.

Else

IsReal = False	' If not.

End If

End Function


Beep Statement

Example

Sounds a tone through the computer's speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depends on hardware, which may vary among computers.


Beep Statement Example

The example uses Beep to sound a tone in the computer speaker if Answer is less than 1 or greater than 3.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg	' Declare variables.

Do

Answer = InputBox("Enter a value from 1 to 3.")

If Answer >= 1 And Answer <= 3 Then	' Check range.

Exit Do	' Exit Do...Loop.

Else

Beep	' Beep if not in range.

End If

Loop

MsgBox "You entered a value in the proper range."

End Sub


InputBox, InputBox$ Function

See Also	Example

Displays a prompt in a dialog box, wait for the user to input text or choose a button, and returns the contents of the text box.

Syntax

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

Remarks

InputBox returns a Variant of Vartype 8 (String); InputBox$ returns a String.

The InputBox[$] function has these parts:

Part	Description

prompt	String expression displayed as the message in the dialog box.  The maximum length of prompt is approximately 255 characters depending on the width of the characters used.  If prompt will consist of more than one line, be sure to include a carriage return (ANSI character 13) and a linefeed (ANSI character 10) between each line.

title	String expression displayed in the title bar of the dialog box.  If you omit the title, nothing is placed in the title bar.

default	String expression displayed in the text box as the default response if no other input is provided.  If you omit default, the text box is displayed empty.

xpos	Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen.  If you omit xpos, you must also omit ypos.  If xpos and ypos are omitted, the dialog box is horizontally centered and vertically positioned approximately one third of the way down the screen.  If you omit either title or default or both but include xpos and ypos, you must still include the commas that separate the arguments.

ypos	Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen.

If the user chooses the OK button or presses Enter, the InputBox[$] function returns whatever is in the text box.  If the user chooses the Cancel button, the function returns a zero-length string ("").


See Also

MsgBox Function, MsgBox Statement


InputBox, InputBox$ Function Example

The example prompts the user with a message and returns the user-entered value.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, DefVal, Msg, Title	' Declare variables.

Msg = "Enter a value from 1 to 3."	' Set prompt.

Title = "InputBox Demo"	' Set title.

DefVal = "1"	' Set default return value.

Do

Answer = InputBox(Msg, Title, DefVal)	' Get user input.

Loop Until Answer >= 1 And Answer <= 3

MsgBox "You entered " & Answer	' Dsiplay message.

End Sub


MsgBox Function, MsgBox Statement

See Also	Example

Displays a message in a dialog box and waits for the user to choose a button.  The MsgBox function returns a value indicating which button the user has chosen; the MsgBox statement does not.

Function Syntax

MsgBox(msg [, [type][, title] ] )

Statement Syntax

MsgBox msg [, [type][, title] ]

Remarks

The MsgBox function and statement both have these parts:

Part	Description

msg	String expression displayed as the message in the dialog box.

type	Optional numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality.  The following table illustrates the values used and the meaning of each group of values:

Symbolic Constant	Value	Meaning

MB_OK	0	Display OK button only.

MB_OKCANCEL	1	Display OK and Cancel buttons.

MB_ABORTRETRYIGNORE	2	Display Abort, Retry, and Ignore buttons.

MB_YESNOCANCEL	3	Display Yes, No, and Cancel buttons.

MB_YESNO	4	Display Yes and No buttons.

MB_RETRYCANCEL	5	Display Retry and Cancel buttons.

MB_ICONSTOP	16

MB_ICONQUESTION	32

MB_ICONEXCLAMATION	48

MBICONINFORMATION	64

MB_DEFBUTTON1	0	First button is default.

MB_DEFBUTTON2	256	Second button is default.

MB_DEFBUTTON3	512	Third button is default.

MB_APPLMODAL	0	Application modal.  The user must respond to the message box before continuing work in the current application.

MB_SYSTEMMODAL	4096	System modal.  All applications are suspended until the user responds to the message box.

The first group of values (1-5) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style;  the third group (0, 256, 512) determines which button is the default; and the fourth group (0, 4096) determines the modality of the message box.  When adding numbers to create a final value for the argument type, use only one number from each group. If omitted, the default value for type is 0.

title	String expression displayed in the title bar of the dialog box.  If you omit the argument title, MsgBox uses "Microsoft Visual Basic" as the default title for applications running in the Visual Basic development environment and the application name for executable files created by Visual Basic.

For application modal message boxes, MsgBox displays a maximum of 1024 characters.  Longer messages are truncated after the 1024th character.  Message strings longer than 255 characters with no intervening spaces are truncated after the 255th character.  For system modal message boxes, the number of characters you can display depends on screen resolution and whether or not the string to be displayed is on one or more lines.

MsgBox breaks lines automatically at the right edge of the dialog box.  If you want to set line breaks yourself, place a linefeed (ANSI character 10) before the first character of the text that is to begin each new line.  For system modal message boxes in Microsoft Windows 3.0 only, the linefeed character does not cause a line to wrap.

The value returned by the MsgBox function indicates which button has been selected, as shown in the following table:

Symbolic Constant	Value	Meaning

IDOK	1	OK button selected.

IDCANCEL	2	Cancel button selected.

IDABORT	3	Abort button selected.

IDRETRY	4	Retry button selected.

IDIGNORE	5	Ignore button selected.

IDYES	6	Yes button selected.

IDNO	7	No button selected.

If the dialog box displays a Cancel button, pressing the Esc key has the same effect as choosing Cancel.

Note	Symbolic constants for all message box definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

InputBox, InputBox$ Function


MsgBox Function, MsgBox Statement Example

The example uses MsgBox to display a critical-error message in a dialog box with a Yes button and a No button.  The No button is the default response.  The MsgBox function returns a value based on the button chosen by the user.  The MsgBox statement uses that value to display a message that indicates which button was chosen.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const MB_OK = 0, MB_OKCANCEL = 1	' Define buttons.

Const MB_YESNOCANCEL = 3, MB_YESNO = 4

Const MB_ICONSTOP = 16, MB_ICONQUESTION = 32	' Define Icons.

Const MB_ICONEXCLAMATION = 48, MB_ICONINFORMATION = 64

Const MB_DEFBUTTON2 = 256, IDYES = 6, IDNO = 7	' Define other.

Dim DgDef, Msg, Response, Title	' Declare variables.

Title = "MsgBox Demo"

' Put together a sample message box with all the proper components.

Msg = "This is a sample of a critical-error message."

Msg = Msg & " Do you want to continue?"

DgDef = MB_YESNO + MB_ICONSTOP + MB_DEFBUTTON2	' Describe dialog.

Response = MsgBox(Msg, DgDef, Title)	' Get user response.

If Response = IDYES Then	' Evaluate response

Msg = "You chose Yes."	' and take appropriate

Else	' action.

Msg = "You chose No or pressed Enter."

End If

MsgBox Msg	' Display action taken.

End Sub


SendKeys Statement

See Also	Example

Sends one or more keystrokes to the active window as if they had been entered at the keyboard.

Syntax

 SendKeys keytext [,wait]

Remarks

The SendKeys statement has these parts:

Part	Description

keytext	String expression sent to the active window.

wait	Numeric expression. If wait is True, keystrokes must be processed before control is returned to the procedure.  If wait is False, control is returned to the procedure immediately after the keys are sent.  If wait is omitted, False is assumed as the default.

Each key is represented by one or more characters.  To specify a single keyboard character, use the character itself.  For example, to represent the letter A, use "A" for keytext.  If you want to represent more than one character, append each additional character to the one preceding it.  To represent the letters A, B, and C, use "ABC" for keytext.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys.  To specify one of these characters, enclose it inside braces.  For example, to specify the plus sign, use {+}.  Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces as well, because in other applications for Microsoft Windows, brackets do have special meaning that may be significant when dynamic-data exchange (DDE) occurs.  To send brace characters, use {{} and {}}.

To specify characters that aren't displayed when you press a key (such as Enter or Tab) and keys that represent actions rather than characters, use the codes shown below:

Key	Code	Key	Code
Backspace	{BACKSPACE} or {BS} or {BKSP}	Break	{BREAK}
Caps Lock	{CAPSLOCK}	Clear	{CLEAR}
Del	{DELETE} or {DEL}	Down Arrow	{DOWN}
End	{END}	Enter	{ENTER} or ~
Esc	{ESCAPE} or {ESC}	Help	{HELP}
Home	{HOME}	Ins	{INSERT}
Left Arrow	{LEFT}	Num Lock	{NUMLOCK}
Page Down	{PGDN}	Page Up	{PGUP}
Print Screen	{PRTSC}	Right Arrow	{RIGHT}
Scroll Lock	{SCROLLLOCK}	Tab	{TAB}
Up Arrow	{UP}	F1	{F1}
F2	{F2}	F3	{F3}
F4	{F4}	F5	{F5}
F6	{F6}	F7	{F7}
F8	{F8}	F9	{F9}
F10	{F10}	F11	{F11}
F12	{F12}	F13	{F13}
F14	{F14}	F15	{F15}
F16	{F16}
To specify keys combined with any combination of Shift, Ctrl, and Alt keys, precede the regular key code with one or more of the following codes:

Key	Code

Shift	+

Control	^

Alt	%

To specify that Shift, Ctrl, and/or Alt should be held down while several other keys are pressed, enclose the keys' code in parentheses.  For example, to have the Shift key held down while E and C are pressed, use "+(EC)".  To have Shift held down while E is pressed, followed by C being pressed without Shift, use "+EC".

To specify repeating keys, use the form {key number};  you must put a space between key  and number.  For example, {LEFT 42} means press the Left Arrow key 42 times; {h 10} means press h 10 times.

Note	SendKeys can't send keystrokes to an application that is not designed to run in Microsoft Windows.  Sendkeys also can't send the Print Screen (PRTSC) key to any application.


See Also

DoEvents Function, DoEvents Statement


SendKeys Statement Example

The example uses Shell to run the Calculator application included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to either quit the Calculator or add some numbers, depending on the user's choice.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, X	' Declare variables.

X = Shell("Calc.exe", 1)	' Shell Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	'  to add each value of I.

SendKeys "=", True	' Get grand total.

AppActivate "Microsoft Visual Basic"	' Return focus to Visual Basic.

Msg = "Choose OK to close Calculator."	' Stop to see results.

MsgBox Msg

AppActivate "Calculator"	' Return focus to Calculator.

SendKeys "%{F4}", True	' Send Alt+F4 to close Calculator.

End Sub


AppActivate Statement

See Also	Example

Activates an application window.

Syntax

AppActivate titletext

Remarks

The argument titletext is a string expression that is the name that appears in the title bar of the application window to activate.  If there is more than one instance of the application, the operating environment arbitrarily selects the one to activate.  The name that appears in the title bar and titletext must match character-for-character, but the comparison is not case sensitive:  "Calculator" and "calculator" appear identical.

The AppActivate statement changes the focus to the named application window but does not affect whether it is maximized or minimized.  Focus moves from the activated application window when the user takes some action to change the focus or close the window.


See Also

Shell Function

SendKeys Statement


AppActivate Statement Example

The example uses the AppActivate statement to change focus between Visual Basic and the Microsoft Windows Calculator application.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim 	I, Msg, X	' Declare variables.

AppActivate "Microsoft Visual Basic"	' Change focus to Visual Basic.

SendKeys "%{ }{Down 3}{Enter}", True	' Minimize Visual Basic

X = Shell("Calc.exe", 1)	' Shell the Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	'  to add each value of I.

SendKeys "=", True	' Get grand total.

AppActivate "Microsoft Visual Basic"	' Focus back to Visual Basic.

Msg = "Choose OK to close Calculator."	' Stop to see results.

MsgBox Msg

AppActivate "Calculator"	' Focus back to Calculator.

SendKeys "%{F4}", True	' Alt+F4 to close Calculator.

AppActivate "Microsoft Visual Basic"	' Change focus back to Visual Basic.

SendKeys "%{ }{Enter}", True	' Restore Visual Basic to size.

End Sub


AddItem Method

See Also	Example

Adds a new item to a list box or combo box or adds a new row to a grid control at run time.

Syntax.

control.AddItem item [,index]

Remarks

The AddItem method has these parts:

Part	Description

control	List box, combo box, or grid control.

item	String expression to add to the control. For grid controls only, use the tab character (character code 09) to separate multiple strings you want inserted into each column of a newly added row.

index	Integer representing the position within the control where the new item or row is placed.  For the first item in a list box or combo box, or for the first row in a grid control,  index = 0.

AddItem places item in the list box, combo box, or grid specified by control.  If you supply a valid value for the optional index, item is placed at that position within the control.  If index is omitted, item is added at the proper sorted position (if Sorted property is True), or to the end of the list (if Sorted is False).


See Also

Clear Method

RemoveItem Method


AddItem Method Example

The example uses AddItem to add 100 items to a list box.  To try this example, paste the code into the Declarations section of a form with a list box control named List1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Entry, I, Msg	' Declare variables

Msg = "Choose OK to add 100 items to your list box."

MsgBox Msg	' Display message.

For I = 1 To 100	' Count from 1 to 100.

Entry = "Entry " & I	' Create entry.

List1.AddItem Entry	' Add the entry.

Next I

Msg = "Choose OK to remove every other entry."

MsgBox Msg	' Display message.

For I = 1 To 50	' Determine how to

List1.RemoveItem I	' remove every other

Next I	' item.

Msg = "Choose OK to remove all items from the list box."

MsgBox Msg	' Display message.

List1.Clear	' Clear list box.

End Sub


Clear Method

See Also	Syntax 1 Example	Syntax 2 Example

Clears the contents of a list box or combo box.  Alternatively, clears the contents of the operating environment Clipboard.

Syntax 1

control.Clear

Syntax 2

Clipboard.Clear

Remarks

In Syntax 1, control may either be a list box or a combo box.  In Syntax 2, only the special Clipboard object is allowed.


See Also

AddItem Method

Clipboard Object

RemoveItem Method


Clear Method - Syntax 1 Example

The example uses the Clear method to clear all items from a list box.  To try this example, paste the code into the Declarations section of a form with a list box control named List1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Entry, I, Msg	' Declare variables

Msg = "Choose OK to add 100 items to your list box."

MsgBox Msg	' Display message.

For I = 1 To 100	' Count from 1 to 100.

Entry = "Entry " & I	' Create entry.

List1.AddItem Entry	' Add the entry.

Next I

Msg = "Choose OK to remove every other entry."

MsgBox Msg	' Display message.

For I = 1 To 50	' Determine how to

List1.RemoveItem I	' remove every other

Next I	' item.

Msg = "Choose OK to remove all items from the list box."

MsgBox Msg	' Display message.

List1.Clear	' Clear list box.

End Sub


Clear Method - Syntax 2 Example

The example uses the Clear method to clear the Clipboard.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2	' Define bitmap format.

Dim Msg	' Declare variable.

On Error Resume Next	' Set up error handling.

Msg = "Choose OK to load a bitmap onto the Clipboard."

MsgBox Msg	' Display message.

Clipboard.Clear	' Clear Clipboard.

Clipboard.SetData LoadPicture("PAPER.BMP")	' Get bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub

End If

Msg = "A bitmap is now on the Clipboard. Choose OK to copy "

Msg = Msg & "the bitmap from the Clipboard to the form."

MsgBox Msg	' Display message.

Picture = Clipboard.GetData()	' Copy from Clipboard.

Msg = "Choose OK to clear the picture box."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture box.

End Sub


Cls Method

See Also	Example

Clears graphics and text generated at run time from a form or picture.

Syntax

[object.]Cls

Remarks

The object can be a form or picture box control.  If object is omitted, Cls clears text and graphics from the current form.

Cls clears text and graphics generated at run time with graphics and printing statements.  Background bitmaps set using the Picture property and controls placed on the form at design time are not affected by Cls.  Graphics and text placed on a form, image, or picture box control while AutoRedraw property is True are also not affected if AutoRedraw is set to False before Cls is executed.  That is, some degree of permanence can be achieved by carefully manipulating the AutoRedraw property of a form, image, or picture box control.

After Cls is executed, the CurrentX and CurrentY properties of a form, image, or picture box control are reset to 0.


See Also

AutoRedraw Property

CurrentX Property

CurrentY Property


Cls Method Example

The example uses the Cls method to erase printed information on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

AutoRedraw = -1	' Turn on AutoRedraw.

ForeColor = QBColor(15)	' Set foreground to white.

BackColor = QBColor(1) 	' Set background to blue.

FillStyle = 7	' Set diagonal crosshatch.

Line (0, 0)-(ScaleWidth, ScaleHeight), , B	' Put box on form.

Msg = "This is information printed on the form background."

CurrentX = ScaleWidth / 2 - TextWidth(Msg) / 2	' Set X position.

CurrentY = 2 * TextHeight(Msg)	' Set Y position.

Print Msg	' Print message to form.

Msg = "Choose OK to clear the information and background "

Msg = Msg & "pattern just displayed on the form."

MsgBox Msg	' Display message.

Cls	' Clear form background.

End Sub


Drag Method

See Also	Example

Begins, ends, or cancels dragging controls.

Syntax

[control.] Drag [action]

Remarks

The Drag method has the following parts:

Part	Description

control	Control to be dragged.  The Drag method can be used on any control except Line, Menu, Shape, or Timer.

action	Integer value from 0 to 2, inclusive, that indicates the action to perform.  If action is omitted, start dragging control.

Value	Meaning

0	Cancel drag operation..

1	Begin dragging control.

2	End dragging, that is, drop control.

Use of the Drag method to control dragging and dropping is required only when the DragMode property of the control to drag is set to 0 (Manual).  However, you may still use Drag on a control whose DragMode property is 1 (Automatic).

If you want the mouse pointer to change while the control is being dragged, use either the DragIcon property or the MousePointer property to define your pointer.  Note that the MousePointer property is only used if no DragIcon is specified.


See Also

DragDrop Event

DragIcon Property

DragMode Property

DragOver Event

MousePointer Property


Drag Method Example

The example uses the Drag method to drag the file name of a bitmap file to a picture box where the bitmap is displayed.  To try this example, paste all of the code into the Declarations section of a form that contains a drive list box, a directory list box, a file list box, a picture box, and a label.  Use the default names for the controls in all cases.  Size and position all controls so they can be easily seen and used.  The size and position of the label is unimportant as it will be changed at run time.  When the program begins you will be able to browse your file system and load any bitmaps.  Once you've located a bitmap that you want to display, click the file name of that bitmap and drag it to the picture control.

Sub Form_Load ()

Picture1.AutoSize = -1	' Turn on AutoSize.

Label1.Visible = 0	' Make the label invisible.

File1.Pattern = "*.BMP; *.ICO; *.WMF"	' Set file patterns.

End Sub

Sub Dir1_Change ()	' Any change in Dir1

File1.Path = Dir1.Path	' is reflected in File1.

End Sub

Sub Drive1_Change ()	' Any change in Drive1

Dir1.Path = Drive1.Drive	' is reflected in Dir1.

End Sub

Sub File1_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

Dim DY	' Declare variable.

DY = TextHeight("A")	' Get height of one line.

Label1.Move File1.Left, File1.Top + Y - DY /2, File1.Width, DY

Label1.Drag	' Drag label outline.

End Sub

Sub Dir1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

If State = 0 Then Source.MousePointer = 12	' Change pointer to no drop.

If State = 1 Then Source.MousePointer = 0	' Use default mouse pointer.

End Sub

Sub Drive1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

If State = 0 Then Source.MousePointer = 12	' Change pointer to no drop.

If State = 1 Then Source.MousePointer = 0	' Use default mouse pointer.

End Sub

Sub Form_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

If State = 0 Then Source.MousePointer = 12	' Change pointer to no drop.

If State = 1 Then Source.MousePointer = 0	' Use default mouse pointer.

End Sub

Sub File1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

On Error Resume Next

If State = 0 And Right$(File1.Filename,4) = ".ico" Then

Label1.DragIcon = LoadPicture(File1.Path + "\" + File1.Filename)

If Err Then MsgBox "The icon file could not be loaded."

ElseIf State = 1 Then

Label1.DragIcon = LoadPicture ()	' Use no drag icon.

End If

End Sub

Sub Picture1_DragDrop (Source As Control, X As Single, Y As Single)

On Error Resume Next

Picture1.Picture = LoadPicture(File1.Path + "\" + File1.Filename)

If Err Then MsgBox "The picture file could not be loaded."

End Sub


GetData Method

See Also	Example

Returns a picture from the operating environment Clipboard object.

Syntax

Clipboard.GetData ([format])

Remarks

The argument format specifies one of the following Clipboard formats recognized by Visual Basic:

Symbolic Constant	Value	Clipboard Format

CF_BITMAP	2	Bitmap (.BMP files)

CF_METAFILE	3	Metafile (.WMF files)

CF_DIB	8	Device-independent bitmap

CF_PALETTE	9	Color palette

If format is 0 or omitted, GetData automatically uses the appropriate format.

If there is no picture on the Clipboard that matches the expected format, a null picture is returned.  If only a color palette is present on the Clipboard, a minimum size (1 x 1) device-independent bitmap is created.

Note	Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetFormat Method

GetText Method

SetData Method


GetData Method Example

The example uses the GetData method to copy a bitmap from the Clipboard to a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2	' Define bitmap format.

Dim Msg	' Declare variable.

On Error Resume Next	' Set up error handling.

Msg = "Choose OK to load a bitmap onto the Clipboard."

MsgBox Msg	' Display message.

Clipboard.Clear	' Clear Clipboard.

Clipboard.SetData LoadPicture("PAPER.BMP")	' Get bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub

End If

Msg = "A bitmap is now on the Clipboard. Choose OK to copy "

Msg = Msg & "the bitmap from the Clipboard to the form "

MsgBox Msg	' Display message.

Picture = Clipboard.GetData()	' Copy from Clipboard.

Msg = "Choose OK to clear the picture box."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture box.

End Sub


GetFormat Method

See Also	Example

Returns an integer indicating whether there is an item in the operating environment Clipboard that matches a specified format.

Syntax

Clipboard.GetFormat (format)

Remarks

The argument format specifies one of the following Clipboard formats recognized by Visual Basic:

Symbolic Constant	Value	Clipboard Format

CF_LINK	&HBF00	DDE Conversation information

CF_TEXT	1	Text

CF_BITMAP	2	Bitmap (.BMP files)

CF_METAFILE	3	Metafile.(.WMF files)

CF_DIB	8	Device-independent bitmap

CF_PALETTE	9	Color palette

The GetFormat method returns True if there is an item on the Clipboard that matches the specified format.  Otherwise, it returns False.

For CF_DIB and CF_BITMAP formats, any palette on the Clipboard will be used when the picture is displayed.

Note  Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in anymodule in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetData Method

GetText Method


GetFormat Method Example

The example uses the GetFormat method to determine the format of data on the Clipboard.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

' Define bitmap formats.

Const CF_TEXT = 1, CF_BITMAP = 2, CF_DIB = 8, CF_PALETTE = 9

Dim ClpFmt, Msg	' Declare variables

On Error Resume Next	' Set up error handling.

If Clipboard.GetFormat(CF_TEXT) Then ClpFmt = ClpFmt + 1

If Clipboard.GetFormat(CF_BITMAP) Then ClpFmt = ClpFmt + 2

If Clipboard.GetFormat(CF_DIB) Then ClpFmt = ClpFmt + 4

Select Case ClpFmt

Case 1

Msg = "The Clipboard contains only text."

Case 2, 4, 6

Msg = "The Clipboard contains only a bitmap."

Case 3, 5, 7

Msg = "The Clipboard contains text and a bitmap."

Case Else

Msg = "There is nothing on the Clipboard."

End Select

MsgBox Msg	' Display message.

End Sub


GetText Method

See Also	Example

Returns a text string from the operating environment Clipboard.

Syntax

Clipboard.GetText ([format])

Remarks

The argument format specifies one of the following Clipboard formats recognized by Visual Basic:

Symbolic Constant	Value	Clipboard Format

CF_LINK	&HBF00	DDE conversation information

CF_TEXT	1	Text

If format is omitted, CF_TEXT is assumed.

If there is no text string on the Clipboard that matches the expected format, a zero-length string ("") is returned.

Note	Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetData Method

GetFormat Method

SetText Method


GetText Method Example

The example uses the GetText method to copy a text string from the Clipboard to a string variable.  To try this example, paste the code into the Declarations section of a form with a text box named Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_TEXT = 1	' Define bitmap format.

Dim I, Msg, Temp	' Declare variables

On Error Resume Next	' Set up error handling.

Msg = "Type anything you like into the text box below."

Text1.Text = InputBox(Msg)	' Get text from user.

Msg = "Choose OK to copy the contents of the text box "

Msg = Msg & "to the Clipboard."

MsgBox Msg	' Display message.

ClipBoard.Clear	' Clear Clipboard.

Clipboard.SetText Text1.Text	' Put text on Clipboard.

If Clipboard.GetFormat(CF_TEXT) Then

Text1.Text = ""	' Clear the text box.

Msg = "The text is now on the Clipboard. Choose OK "

Msg = Msg & "to copy the text from the Clipboard back "

Msg = Msg & "to the text box."

MsgBox Msg	' Display message.

Temp = Clipboard.GetText(CF_TEXT)	' Get Clipboard text.

For I = Len(Temp) To 1 Step -1	' Reverse the text.

Text1.Text = Text1.Text & Mid(Temp, I, 1)

Next I

Else

Msg = "There is no text on the Clipboard."

MsgBox Msg	' Display error message.

End If

End Sub


Hide Method

See Also	Example

Hides a form, but does not unload it.

Syntax

[form.]Hide

Remarks

The argument form is the name of the form or MDI form to hide.

When a form is hidden, it is removed from the screen and its Visible property is set to False .  A hidden form's controls are not accessible to the user, but they are available to the running Visual Basic program, to other processes that may be communicating with the application through dynamic data exchange (DDE), and to timer events.

When a form is hidden, control does not return to the user until all code in the event procedure that caused the form to be hidden has finished executing.

If the form is not loaded when the Hide method is invoked, it is loaded, but not shown.

While you can use the Hide method to hide an MDI form, you cannot hide an MDI child form.


See Also

Load Statement

Show Method

Unload Statement

Visible Property


Hide Method Example

The example uses the Hide method to hide a form.  To try this example, paste the code into the Declarations section of a non-MDI form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

Hide	' Hide form.

Msg = "Choose OK to make the form reappear."

MsgBox Msg	' Display message.

Show	' Show form again.

End Sub


Load Statement

See Also	Example

Loads a form or control into memory.

Syntax

Load object

Remarks

The argument object is a form, MDI form, or control array element to load.

It is not necessary to use the Load statement with forms unless you want to load a form without displaying it.  Any reference to a form (except in a Set or If...TypeOf statement) automatically loads it if it is not already loaded.  For example, the Show method loads an unloaded form before displaying it.  Once the form is loaded, all properties for the form and its controls can be altered by the program, whether or not the form is actually visible.  Under some circumstances, you may want to load all your forms during intitialization and display them later as they are needed.

When more than one instance of a form is loaded, each form has its own set of properties and variables that can be changed independently from all other instances of the form.

When Visual Basic loads a form, it sets form properties to their initial values, then performs the Load event procedure.  When an application starts, Visual Basic automatically loads and displays the application's start up form.

If you load an MDI child form before loading the MDI form, the MDI form is automatically loaded before the child form is loaded.  Loading an MDI child form causes it to be visible immediately after the Form_Load event ends because MDI child forms cannot be hidden.

The standard dialog boxes produced by Visual Basic functions such as MsgBox and InputBox do not need to be loaded, shown, or unloaded, but can simply be invoked directly.


See Also

Hide Method

InputBox Function

MsgBox Function

Show Method

Unload Statement


Load Statement Example

The example uses the Load statement to load a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg	' Declare variable.

Unload Form1	' Unload form.

Msg = "Form1 has been unloaded. Choose Yes to load and "

Msg = Msg & "display the form. Choose No to load the form "

Msg = Msg & "and leave it invisible."

Answer = MsgBox(Msg, 4)	' Get user response.

If Answer = 6 Then	' Evaluate answer.

Show	' If Yes, show form.

Else

Load Form1	' If No, just load it.

Msg = "Form1 is now loaded. Choose OK to display it."

MsgBox Msg	' Display message.

Show	' Show form.

End If

End Sub


LoadPicture Function

See Also	Example

Loads a picture into a form, picture box, or image control.

Syntax

LoadPicture([stringexpression])

Remarks

The argument stringexpression is the name of a picture file to be loaded.  Pictures are cleared from forms, picture boxes, and image controls by assigning LoadPicture with no argument.

Picture files recognized by Visual Basic include bitmaps (.BMP), icons (.ICO), run-length encoded files (.RLE), and metafile (.WMF) files.

To load pictures for display in a picture box, image control, or as the background of a form, the return value of LoadPicture must be assigned to the Picture property of the object on which the picture is displayed.  For example:

Picture = LoadPicture("PARTY.BMP")

Picture1.Picture = LoadPicture("PARTY.BMP")

To load icon files (.ICO) to the form icon, the return value of LoadPicture must be assigned to the Icon property of form:

Icon = LoadPicture("MYICON.ICO")

Icons can also be assigned to the DragIcon property of all controls except timers and menus.  For example:

Command1.DragIcon = LoadPicture("MYICON.ICO")

Load a picture file into the operating environment Clipboard using LoadPicture as follows:

Clipboard.SetData LoadPicture("PARTY.BMP")


See Also

DragIcon Property

Icon Property

Picture Property

SavePicture Statement

SetData Method


LoadPicture Function Example

The example uses the LoadPicture function to load a picture into a form and to clear the picture from the form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variables.

On Error Resume Next	' Set up error handling.

Height = 3990: Width = 4890	' Set height and width.

Picture = LoadPicture("PAPER.BMP")	' Load bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub	' Quit if error occurs.

End If

Msg = "Choose OK to clear the bitmap from the form."

Msgbox Msg

Picture = LoadPicture()	' Clear form.

End Sub


Move Method

See Also	Example

Moves a form or control.

Syntax

[object.]Move left[, top[, width[, height] ] ]

Remarks

The Move method has these parts:

Part	Description

object	Form or control to move.  May be any control except timers and menus.

left	Single-precision value indicating the horizontal coordinate for the left edge of object.

top	Single-precision value indicating the vertical coordinate for the top edge of object.

width	Single-precision value indicating the new width of object.

height	Single-precision value indicating the new height of object.

Only the left argument is required.  However, to specify any other arguments, you must specify all arguments that appear in the syntax before the argument you want to specify.  For example, you cannot specify width without specifying left and top.  Any trailing arguments that are unspecified remain unchanged.

For forms and for controls within frames, the coordinate system is always twips.  Moving a form on the screen or moving a control within a frame is always relative to the origin (0,0), which is the upper-left corner.  When moving controls on a form or in a picture control, the coordinate system of the object is used.  The coordinate system is set using ScaleHeight, ScaleWidth, ScaleLeft and ScaleRight properties.


See Also

Height Property

Left Property

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleWidth Property

Top Property

Width Property


Move Method Example

The example uses the Move method to move a form around on the screen.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim In, Msg	' Declare variables.

Msg = "Choose OK to resize and move this form by "

Msg = Msg & "changing the value of properties."

MsgBox Msg	' Display message.

In = 1440	' Set inch in twips.

Width = 4 * In	' Set width.

Height = 2 * In	' Set height.

Left = 0	' Set left to origin.

Top = 0	' Set top to origin.

Msg = "Now choose OK to resize and move this form "

Msg = Msg & "using the Move Method."

MsgBox Msg	' Display message.

Move Screen.Width - 2 * In, Screen.Height - In, 2 * In, In

End Sub


Refresh Method

Example

Forces an immediate update of a form or control.

Syntax

[object.]Refresh

Remarks

The object is the form or control to update.  Refresh cannot be used on MDI Forms, but can be used on MDI child forms.  You cannot use Refresh on Menu or Timer controls.

Generally, updating a form or control is handled automatically when the idle loop is reached. However, there may be situations where you want the form or control updated before such an event takes place. For example, if you use a file list box, a directory list box, or a drive list box, to show the current status of the file system, you can use Refresh to update the status anytime a change is made.


Refresh Method Example

The example uses the Refresh method to update a file list box as test files are being created.  To try this example, paste the code into the Declarations section of a form with a file list box named File1.  Then press F5 and click the form.

Sub Form_Click ()

Dim FName, I, Msg	' Declare variables.

File1.Pattern = "TestFile.*"	' Set file pattern.

For I = 1 To 8	' Do 8 times.

FName = "TESTFILE." & I

Open FName For Output As FreeFile	' Create null 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


RemoveItem Method

See Also	Example

Removes an item from a list box or combo box or removes a row from a grid control at run time

Syntax.

control.RemoveItem index

Remarks

The RemoveItem method has these parts:

Part	Description

control	List box, combo box, or grid control.

index	Integer representing the position within the control of the item or row to remove.  For the first item in a list box or combo box, or for the first row in a grid control,  index = 0.


See Also

AddItem Method

Clear Method


RemoveItem Method Example

The example uses RemoveItem to remove entries from a list box.  To try this example, paste the code into the Declarations section of a form with a list box control named List1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Entry, I, Msg	' Declare variables.

Msg = "Choose OK to add 100 items to your list box."

MsgBox Msg	' Display message.

For I = 1 To 100	' Count from 1 to 100.

Entry = "Entry " & I	' Create entry.

List1.AddItem Entry	' Add the entry.

Next I

Msg = "Choose OK to remove every other entry."

MsgBox Msg	' Display message.

For I = 1 To 50	' Determine how to

List1.RemoveItem I	' remove every other

Next I	' item.

Msg = "Choose OK to remove all items from the list box."

MsgBox Msg	' Display message.

List1.Clear	' Clear list box.

End Sub


SavePicture Statement

See Also	Example

Saves a picture from a form, picture box, or image control into a file.

Syntax

SavePicture picture, stringexpression

Remarks

The SavePicture statement has these parts:

Part	Description

picture	Picture or Image property from which the picture file is to be created.

stringexpression	File name of the picture file to save.

If a picture was loaded from file to the Picture property, either at design time or at run time, it is saved using the same format as the original file. Pictures from the Image property are always saved as bitmap (.BMP) files.


See Also

Image Property

LoadPicture Function

Picture Property


SavePicture Statement Example

The example uses the SavePicture statement to save a picture drawn on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, Limit, Msg, Radius	' Declare variables.

ScaleMode = 3	' Set scale to pixels.

AutoRedraw = -1	' Turn on AutoRedraw.

Width = Height	' Change width to match height.

CX = ScaleWidth / 2	' Set X position.

CY = ScaleHeight / 2	' Set Y position.

Limit = CX	' Limit size of circles.

For Radius = 0 To Limit	' Set radius.

Circle (CX, CY), Radius, RGB(Rnd * 255, Rnd * 255, Rnd * 255)

DoEvents	' Yield for other processing.

Next Radius

Msg = "Choose OK to save the graphics from this form "

Msg = Msg & "to a bitmap file."

MsgBox Msg

SavePicture Image, "TEST.BMP"	' Save picture to file.

End Sub


SetData Method

See Also	Example

Puts a picture in the operating environment Clipboard using the specified format.

Syntax

Clipboard.SetData data,[ format]

Remarks

The SetData method has these parts:

Part	Description

data	Picture (Image or Picture property) to place on the Clipboard.

format	One of the following Clipboard formats recognized by Visual Basic. If format is 0 or omitted, SetData automatically determines the format.

Symbolic Constant	Value	Clipboard Format

CF_BITMAP	2	Bitmap (.BMP files)

CF_METAFILE	3	Metafile (.WMF files)

CF_DIB	8	Device-independent bitmap

CF_PALETTE	9	Color palette

For the CF_BITMAP format, any associated color palette will be copied to the Clipboard along with the bitmap.

Note  Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT. When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetData Method

GetFormat Method


SetData Method Example

The example uses the SetData method to place a bitmap onto the Clipboard.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2	' Define bitmap format.

Dim Msg	' Declare variable.

On Error Resume Next	' Set up error handling.

Msg = "Choose OK to load a bitmap onto the Clipboard."

MsgBox Msg	' Display message.

Clipboard.Clear	' Clear Clipboard.

Clipboard.SetData LoadPicture("PAPER.BMP") ' Get bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub

End If

Msg = "A bitmap is now on the Clipboard. Choose OK to copy "

Msg = Msg & "the bitmap from the Clipboard to the form "

MsgBox Msg	' Display message.

Picture = Clipboard.GetData()	' Copy from Clipboard.

Msg = "Choose OK to clear the picture box."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture box.

End Sub


SetFocus Method

See Also	Example

Sets the focus to a form or control.

Syntax

object.SetFocus

Remarks

The object must be a form, MDI form, or control  which can gain the focus.  The SetFocus method can be used on any control except Frame, Image, Line, Menu, Shape and Timer.  After SetFocus is executed, any user input is directed to the specified form or control.

You can only set focus to a visible form or control.  Since a form and controls on a form are not visible until the form's Load event has finished, you cannot use SetFocus to set the focus to the form being loaded in its own Load event unless you also use the Show method to show the form before the completion of the Form_Load procedure.

You also cannot set the focus to a form or control if the Enabled property is set to False.  If the Enabled property has been set to False at design time, you must first set it to True before it can gain the focus using SetFocus.


See Also

Enabled Property

Load Event

Show Method


SetFocus Method Example

The example uses the SetFocus method to change focus between two command buttons.  To try this example, paste the code into the Declarations section of a form named Form1 that has two command buttons.  Use the default names for the command buttons.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

Msg = "Choose OK to watch the focus change to the other control."

MsgBox Msg	' Display message.

If Screen.ActiveControl.Caption = "Command1" Then

Command2.SetFocus	' Set focus to button 2.

Else

Command1.SetFocus	' Set focus to button 1.

End If

End Sub


SetText Method

See Also	Example

Puts a text string in the operating environment Clipboard using the specified Clipboard format.

Syntax

Clipboard.SetText data [,format]

Remarks

The SetText method has these parts:

Part	Description

data	String data to be placed on the Clipboard.

format	One of the following Clipboard formats recognized by Visual Basic.  If format is omitted, CF_TEXT is assumed.

Symbolic Constant	Value	Clipboard Format

CF_LINK	&HBF00	DDE conversation information

CF_TEXT	1	Text

Note  Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT. When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetFormat Method

GetText Method

SetData Method


SetText Method Example

The example uses the SetText method to copy text from a text box to the Clipboard. To try this example, paste the code into the Declarations section of a form with a text box named Text1. Then press F5 and click the form.

Sub Form_Click ()

Const CF_TEXT = 1	' Define bitmap format.

Dim I, Msg, Temp	' Declare variables.

On Error Resume Next	' Set up error handling.

Msg = "Type anything you like into the text box below."

Text1.Text = InputBox(Msg)	' Get text from user.

Msg = "Choose OK to copy the contents of the text box "

Msg = Msg & "to the Clipboard."

MsgBox Msg	' Display message.

ClipBoard.Clear	' Clear Clipboard.

Clipboard.SetText Text1.Text	' Put text on Clipboard.

If Clipboard.GetFormat(CF_TEXT) Then

Text1.Text = ""	' Clear the text box.

Msg = "The text is now on the Clipboard. Choose OK "

Msg = Msg & "to copy the text from the Clipboard back "

Msg = Msg & "to the text box."

MsgBox Msg	' Display message.

Temp = Clipboard.GetText(CF_TEXT)	' Get Clipboard text.

For I = Len(Temp) To 1 Step -1	' Reverse the text.

Text1.Text = Text1.Text & Mid(Temp, I, 1)

Next I

Else

Msg = "There is no text on the Clipboard."

MsgBox Msg	' Display error message.

End If

End Sub


Show Method

See Also	Example

Displays a form.

Syntax

[form.]Show [style]

Remarks

The Show method has these parts:

Part	Description

form	Form or MDI form to display. If not specified, the form associated with the current form module is displayed.

style	Integer value that determines if the form is modal or modeless.  If style is 0, the form is modeless, if style is 1, the form is modal.

If the specified form is not loaded when the Show method is invoked, Visual Basic automatically loads it.

When a modeless form is displayed, Visual Basic code that occurs after the Show method is executed as it is encountered.  When a modal form is displayed, no Visual Basic code after the Show method is executed until the form is hidden or unloaded.

When displaying a modal form, it is also important to note that no user input (keyboard or mouseclick) can occur in any other form until the modal form is hidden or unloaded.  The program must hide or unload a modal form (usually in response to some use action) before further user input can occur.  MDI forms cannot be shown modally.

Although other forms in your application are disabled when a modal form is displayed, other applications are not.

The startup form of an application is automatically shown after its load event is executed.


See Also

Activate Event

Hide Method

Load Statement

Unload Statement

Visible Property


Show Method Example

The example uses the Show method to show a hidden form.  To try this example, paste the code into the Declarations section of a non-MDI form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

Hide	' Hide form.

Msg = "Choose OK to make the form reappear."

MsgBox Msg	' Display message.

Show	' Show form again.

End Sub


Unload Statement

See Also	Example

Unloads a form or control from memory.

Syntax

Unload object

Remarks

The argument object is the form or control array element to unload.

Unloading a form or control may be necessary or expedient in some cases where the memory used is needed for something else or when you need to reset properties to their original value.

Before a form is unloaded, the Query_Unload event occurs, followed by the Form_Unload event.  Setting the Cancel argument to True in either of these events keeps the form from being unloaded.  For MDI forms, the MDI form Query_Unload event occurs, followed by the Query_Unload event and Form_Unload event for each MDI child form, and finally the MDI form Form_Unload event

When a form is unloaded, all controls placed on the form at run time are no longer accessible.  Controls placed on the form at design time remain intact, although any run-time changes to those controls and their properties are lost when the form is reloaded.  All changes to form properties are also lost.  Note that when a form is unloaded, only the displayed component is unloaded.  The code associated with the form module remains in memory.

Only control array elements added to a form at run-time can be unloaded with the Unload statement.  The properties of unloaded controls are reinitialized when the controls are reloaded.


See Also

Hide Method

Load Statement

QueryUnload Event

Show Method


Unload Statement Example

The example uses the Unload statement to unload a form.  To try this example, paste the code into the Declarations section of a form named Form1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg	' Declare variables

Unload Form1	' Unload form.

Msg = "Form1 has been unloaded. Choose Yes to load and "

Msg = Msg & "display the form. Choose No to load the form "

Msg = Msg & "and leave it invisible."

Answer = MsgBox(Msg, 4)	' Get user response.

If Answer = 6 Then	' Evaluate answer.

Show	' If Yes, show form.

Else

Load Form1	' If No, just load it.

Msg = "Form1 is now loaded. Choose OK to display it."

MsgBox Msg	' Display message.

Show	' Show form.

End If

End Sub


As

The As reserved word is used in these Visual Basic topics:

Declare Statement

Dim Statement

Function Statement

Global Statement

Name Statement

Open Statement

ReDim Statement

Static Statement

Sub Statement


ByVal

The ByVal reserved word is used in these Visual Basic topics:

Call Statement

Declare Statement

Function Statement

Sub Statement


Else

The Else reserved word is used in these Visual Basic topics:

If...Then...Else Statement

Select Case Statement


Is

The Is reserved word is used in these Visual Basic topics:

If...Then...Else Statement

Is Operator

Select Case Statement


New

The New reserved word is used in these Visual Basic topics:

Dim Statement

Global Statement

Set Statement

Static Statement


Step

The Step reserved word is used in these Visual Basic topics:

Circle Method

For...Next Statement

Line Method

PSet Method


To

The To reserved word is used in these Visual Basic statements:

Dim Statement

For...Next Statement

Global Statement

Lock, Unlock Statements

ReDim Statement

Select Case Statement

Static Statement


Shared

The Shared reserved word is used in these Visual Basic topics:

Dim Statement

Global Statement

Static Statement


Private

The Private reserved word is used in these Visual Basic topics:

Function Statement

Sub Statement


On

The On reserved word is used in these Visual Basic topics:

On Error Statement

On...GoSub, On...GoTo Statements


Next

The Next reserved word is used in these Visual Basic topics:

For...Next Statement

On Error Statement

Resume Statement


Option

The Option reserved word is used in these Visual Basic topics:

Option Base Statement

Option Compare Statement

Option Explicit Statement


True

An intrinsic constant whose value is equal to -1.  Because True is a reserved word, you cannot have any other constant, variable, or procedure whose name is True.


False

An intrinsic constant whose value is equal to 0.  Because False is a reserved word, you cannot have any other constant, variable, or procedure whose name is False.


Me

See Also

Me is a reserved word in Visual Basic that behaves like an implictly-declared variable.  It is automatically available to every procedure (Sub or Function) in a form.  In an environment where you can have more than one instance of a form, Me provides a way to refer to the specific instance of the form where the code is executing.  Using Me is particularly useful when you want to pass information about the current instance of a form to a procedure in another module.  For example, suppose you have the following procedure in a module:

Sub ChangeFormColor(FormName As Form)

FormName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)

End Sub

You can call the procedure and pass the current instance of the form as an argument using the following statement in one of the procedures in your form:

ChangeFormColor Me

In most cases the form referred to by Me is the same as the form referred to by Screen.ActiveForm.  However, it is possible for the two to be different.  Screen.ActiveForm always refers to the form that has the focus while Me always refers to the form where code is executing.  For example, a Timer event can occur in a form that does not have the focus.  When that happens, Screen.ActiveForm refers to the form with focus, while Me refers to the form where the Timer event occurred.


See Also

ActiveForm Property


Arrange Method

See Also	Example

Arranges the windows or icons within an MDI Form.

Syntax

mdiform.Arrange arrangement

Remarks

The Arrange method has these parts:

Part	Description

mdiform	Name of the MDI form whose child windows or icons are to be arranged.

arrangement	One of the following values that indicate how to arrange windows or icons on an MDI Form:

Symbolic Constant	Value	Meaning
CASCADE	0	Cascade all non-minimized MDI child forms.
TILE_HORIZONTAL	1	Tile all non-minimized MDI child forms horizontally.
TILE_VERTICAL	2	Tile all non-minimized MDI child forms vertically.
ARRANGE_ICONS	3	Arrange icons for minimized MDI child forms.
Windows or icons are arranged even if the MDI form is minimized.  Results are visible when the form is next changed from the minimized state

Note	Symbolic constants for arrangment definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

ZOrder Method


Arrange Method Example

The example uses the Arrange Method to arrange windows and icons in an MDI form.  To try this example, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box to see the effects of the Arrange method.

Const FORMCOUNT = 5

Dim F(1 To FORMCOUNT) As New Form1

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

F(I).Caption = "Form" & I + 1	' Change caption on copies.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

F(I).WindowState = 1	' Minimize each copy of F.

Next I

Start = Timer

Do

Loop Until Timer = Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size

MDIForm1.Arrange 3	' Arrange icons

End Select

End Sub


FileCopy Statement

See Also	Example

Copies a file.

Syntax

FileCopy srcfile, destfile

Remarks

The FileCopy statement has these parts:

Part	Description

srcfile	Any string expression that contains an unambiguous (no wildcards) file specification for the file to copy.  The file specification may include optional drive and path information.

destfile	Any string expression that contains an unambiguous (no wildcards) file specification for the file where srcfile is to be copied.  The file specification may also include optional drive and path information.

You cannot copy a file that is already opened by Visual Basic for anything but read-only access.


See Also

Kill Statement

Name Statement


FileCopy Statement Example

The example uses FileCopy to copy one file to another.  When you choose the name of a file in the file list box, you are prompted to enter a destination file name.  To try this example, paste the code into the Declarations section of a form that contains a file list box named File1.  Then press F5 to start.

Sub File1_Click ()

Dim DestFile, Msg	' Declare variables.

On Error GoTo ErrHandler

DestFile = InputBox("Copy to where?")

FileCopy File1.FileName, DestFile	' Copy file to destination.

Exit Sub

ErrHandler:

If Err = 55 Then 	' File already open.

MsgBox "Cannot copy an open file. Close it and try again."

Else

MsgBox "You must specify a complete destination file name."

End If

Resume Next

End Sub


FileDateTime Function

See Also	Example

Returns a String that indicates the date and time a specified file was created or last modified.

Syntax

FileDateTime (filename)

Remarks

The argument filename can be any string expression that contains an unambiguous (no wildcards) file specification.  The file specification may include optional drive and path information.


See Also

FileLen Function

GetAttr Function


FileDateTime Function Example

The example uses FileDateTime to get date and time information about when a file was created or last modified.  File date and time information is displayed in a message box anytime you choose the name of a file in the file list box.  To try this example, paste the code into the Declarations section of a form containing a file list box named File1.  Then press F5 to start.

Sub File1_Click ()

Dim Msg, TimeStamp	' Declare variables.

FName = File1.FileName	' Get selected file name.

TimeStamp = FileDateTime(FName)	' Get file date/time info.

Msg = UCase(FName) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddddd") & " at "

Msg = Msg & Format(TimeStamp, "h:mm AM/PM") & ".  Its size is "

Msg = Msg & FileLen(FName) & " bytes."	' Get file size.

MsgBox Msg	' Display message.

End Sub


FileLen Function

See Also	Example

Returns a Long integer that indicates the length of a file in bytes.

Syntax

FileLen (filename)

Remarks

The argument filename can be any string expression that contains an unambiguous (no wildcards) file specification.  The file specification may include optional drive and path information.

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


See Also

FileDateTime Function

GetAttr Function

LOF Function


FileLen Function Example

The example uses FileLen to get file size information about a file.  File size information is displayed in a message box anytime you choose the name of a file in the file list box.  To try this example, paste the code into the Declarations section of a form containing a file list box named File1.  Then press F5 to start.

Sub File1_Click ()

Dim Msg, TimeStamp	' Declare variables.

FName = File1.FileName	' Get selected file name.

TimeStamp = FileDateTime(FName)	' Get file date/time info.

Msg = UCase(FName) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddddd") & " at "

Msg = Msg & Format(TimeStamp, "h:mm AM/PM") & ".  Its size is "

Msg = Msg & FileLen(FName) & " bytes."	' Get file size.

MsgBox Msg	' Display message.

End Sub


GetAttr Function

See Also	Example

Returns an integer that indicates a file, directory, or volume label's attributes.

Syntax

GetAttr (filename)

Remarks

The argument filename can be any string expression that contains an unambiguous file, directory, or volume label specification.  The file specification may include optional drive and path information.

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

Symbolic Constant	Value	Meaning
ATTR_NORMAL	0	Normal file
ATTR_READONLY	1	Read-only file
ATTR_HIDDEN	2	Hidden file
ATTR_SYSTEM	4	System file
ATTR_VOLUME	8	Volume label
ATTR_DIRECTORY	16	MS-DOS directory
ATTR_ARCHIVE	32	File has changed since last back-up
To determine which attributes are set, use the And operator to perform a bit-wise comparison of the value returned by the GetAttr function and the value of the individual file attribute you want.  If the result is not zero, that attribute is set for the named file.  For example, the Archive attribute is set if the return value of the following And expression is anything but zero, and zero if the Archive attribute is not set:

Result = GetAttr(FName) And ATTR_ARCHIVE

Note	Symbolic constants for file attribute definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

FileAttr Function

SetAttr Statement


GetAttr Function Example

The example uses the GetAttr function to determine the attributes of a file.  Choosing any file in the list box will cause a message box to appear that indicates the files' attributes.  To try this example, paste the code into the Declarations section of a form containing a drive list box, a directory list box, and a file list box, all with default control names.  Then press F5 to start.

Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' Change if drive changes.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Change if directory changes.

End Sub

Sub File1_Click ()

Const ATTR_READONLY = 1, ATTR_HIDDEN = 2	' Declare constants.

Const ATTR_SYSTEM = 4, ATTR_ARCHIVE = 32

Dim Attr, FName, Msg	' Declare variables.

If Right(Dir1.Path) - "\" Then	' See if root file.

FName = Dir1.Path & File1.FileName	' Get file path.

Else

FName = Dir1.Path & "\" & File1.FileName	' Get file path.

End If

Attr = GetAttr(FName)	' Get attributes.

If Attr > 7 Then Attr = Attr Xor ATTR_ARCHIVE	' Disregard Archive

Select Case Attr	' Look up attributes.

Case 0: Msg = "Normal"

Case ATTR_READONLY: Msg = "Read-Only"

Case ATTR_HIDDEN: Msg = "Hidden"

Case ATTR_HIDDEN And ATTR_READONLY: Msg = "Hidden and Read-Only"

Case ATTR_SYSTEM: Msg = "System"

Case ATTR_READONLY And ATTR_SYSTEM: Msg = "Read-Only and System"

Case ATTR_HIDDEN And ATTR_SYSTEM: Msg = "Hidden and System"

Case ATTR_READONLY And ATTR_HIDDEN And ATTR_SYSTEM: Msg = "Read-Only, Hidden, and System"

End Select

MsgBox UCase(FName) & " is a " & Msg & " file."	' Display message.

End Sub


SetAttr Statement

See Also	Example

Sets attribute information for a file.

Syntax

SetAttr filename, attributes

Remarks

The SetAttr statement has the following parts:

Part 	Description

filename	Any string expression that contains an unambiguous (no wildcards) file specification.  The file specification may include optional drive and path information.

attributes	The sum of any of the following values that characterize file attributes as shown:

Symbolic Constant	Value	Meaning
ATTR_NORMAL	0	Normal file
ATTR_READONLY	1	Read-only file
ATTR_HIDDEN	2	Hidden file
ATTR_SYSTEM	4	System file
ATTR_ARCHIVE	32	File has changed since last back-up
If you try to set the attributes of a file that is already opened by Visual Basic for anything but read-only access, a run-time error occurs.

Note	Symbolic constants for file attribute definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

FileAttr Function

GetAttr Statement


SetAttr Statement Example

The example uses the SetAttr statement to set the Archive attribute of a selected file.  Choosing any file in the list box will cause the Archive attribute to be set for that file if it is not already.  To try this example, paste the code into the Declarations section of a form containing a drive list box, a directory list box, and a file list box, all with default control names.  Then press F5 to start.

Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' Change if drive changes.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Change if directory changes.

End Sub

Sub File1_Click ()

Const ATTR_ARCHIVE = 32	' Declare constants.

Dim Fname	' Declare variables.

If Right(Dir1.Path, 1) = "\" Then	' See if root.

FName = UCase(Dir1.Path & File1.FileName)	' Get path.

Else

FName = UCase(Dir1.Path & "\" & File1.FileName)	' Get path.

End If

If GetAttr(FName) And ATTR_ARCHIVE Then	' Check for Archive.

MsgBox FName & " already has the Archive attribute."

Else

SetAttr FName, ATTR_ARCHIVE	' Set Archive.

MsgBox FName & " now has the Archive attribute."

End If

End Sub


ZOrder Method

See Also	Example

Places a specified form or control at the front or back of the z-order within its graphical level.

Syntax

[object.]ZOrder [position]

Remarks

The ZOrder method has these parts:

Part	Description

object	Form, MDI form, or control to be positioned. For controls, object can be any control except a menu or timer.

position	Integer indicating the position of the control relative to other controls.  If position is 0 or omitted, the control is positioned at the front of the z-order.  If position is 1, the control appears at the back of the z-order.

The z-order of controls can be set at design time using Bring To Front and Send To Back choices on the Edit menu.

Within MDI forms, the ZOrder method sends MDI child forms to either the front or the back of the MDI client area, depending on the value of position.  For forms and MDI forms, ZOrder sends the form to either the front or the back of the screen, depending on the value of position.  As a result, forms may appear in front of or behind other running applications.

Note	There are three graphical layers associated with forms and containers.  The back layer is the drawing space, where the results of the graphics methods appear. Next is the middle layer where graphical controls and labels appear.  The front layer is where all non-graphical controls like command buttons, check boxes, and file controls appear.  Anything in one layer covers anything in the layer behind.  The ZOrder method arranges controls only within the layer where the control appears.


See Also

Arrange Method


ZOrder Method Example

The example uses the ZOrder method to position command buttons on a form.  Choosing each button brings it to the front of the z-order.  To try this example, paste the code into the Declarations section of a form that contains a single command button named Command1 whose Index property is set to 0, indicating a control array.  Then press F5 to start.

Sub Form_Load ()

Dim I	' Declare variable.

For I = 1 To 5

Load Command1(I)	' Load new command button.

Command1(I).Left = Command1(I - 1).Left + 250	' Change position.

Command1(I).Top = Command1(I - 1).Top + 250

Command1(I).Caption = "Command" & I + 1	' Change caption.

Command1(I).Visible = True	' Make visible.

Next I

End Sub

Sub Command1_Click (Index As Integer)

Command1(Index).ZOrder 0	' Position button to front.

End Sub


Operator Precedence

See Also

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order.  That order is known as operator precedence.  Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others.  Operations within parentheses are always performed before those outside.  Within parentheses, however, normal operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last.  Within individual categories, operators are evaluated in the order of precedence shown below:

Arithmetic	Comparison	Logical
Exponentiation (^)	Equality (=)	Not
Negation ( - )	Inequality (<>)	And
Multiplication and division (*, / )	Less than (<)	Or
Integer division (\)	Greater than (>)	Xor
Modulo arithmetic (Mod)	Less than or Equal to (<=)	Eqv
Addition and subtraction (+, -)	Greater than or Equal to (>=)	Imp
String concatenation (&)	Like
	Is
Note	All comparison operators have equal precedence, that is, they are evaluated in the left-to-right order in which they appear.

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right.  Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

The string concatenation operator (&) is not really an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators.  Similarly, the Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Other Operators


Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator


Concatenation Operators

& Operator

+ Operator


Other Operators

Is Operator

Like Operator


Logical Operators

And Operator

Eqv Operator

Imp Operator

Not Operator

Or Operator

Xor Operator


^ Operator

See Also	Example

Used to raise a number to the power of an exponent.

Syntax

result = number ^ exponent

Remarks

The number and exponent operands can be any numeric expression.  However, the number operand can be negative only if exponent is an integer value.  When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or a Variant (VarType 5).  However, if either number or exponent is a Null expression, result is also a Null.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


^ Operator Example

The example squares (n^2) a user supplied number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Result As Double	' Declare variables.

N = InputBox("Enter a number.")	' Get number.

Result = N ^ 2	' Square number.

MsgBox N & " squared is " & Result	' Display result.

End Sub


+ Operator

See Also	Example 1	Example 2

Used to sum two numbers.

Syntax

result = operand1 + operand2

Remarks

Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation is to occur.  If at least one operand is not a Variant, the following rules apply:

If	Then
Both expressions are numeric data types (Integer, Long, Single, Double, or Currency)	Add.
Both expressions are Strings	Concatenate.
One expression is a numeric data type and the other is a Variant (other than a Null)	Add.
One expression is a String and the other is a Variant (other than a Null)	Concatenate.
One expression is a Variant containing Empty	Return the remaining operand unchanged as result.
One expression is a numeric data type and the other is a String	A Type mismatch error occurs.
If either operand is a Null (VarType 1), result is a Null.

If both operands are Variant expressions, the VarType of the operands determines the behavior of the + operator in the following way:

If	Then
Both Variant expressions are of VarType 2-7 (numeric data types)	Add.
Both Variant expressions are of VarType 8 (String)	Concatenate.
One Variant expression is of VarType 2-7 (a numeric data type) and the other is of VarType 8 (String)	Add.

For simple arithmetic addition involving only operands of numeric data types, the data type of result is usually the same as that of the most precise operand.  The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency.  The following are exceptions to this order:

When a Single and a Long are added together, the data type of result is converted to a Double.

When the data type of result is a Variant of VarType 3 (Long), VarType 4 (Single), or VarType 7 (Date) that overflows its legal range, result is converted to a Variant of VarType 5 (Double).

When the data type of result is a Variant of VarType 2 (Integer) that overflows its legal range, result is converted to a Variant of VarType 3 (Long).

If one or both operands are Null expressions, result is a Null.  If both operands are Empty, result is an Integer.  However, if only one operand is Empty, the other operand is returned unchanged as result.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


+ Operator Example 1

The example adds a user-supplied number to itself and displays the result  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Result As Double	' Declare variables.

N = InputBox ("Enter a number.")	' Get a number.

Result = N + N	' Add numbers.

MsgBox N & " plus " & N & " is " & (N + N)	' Display result.

End Sub


+ Operator Example 2

The example uses the + operator to concatenate strings.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

MsgBox "Microsoft " + "Visual " + "Basic"	' Display result.

End Sub


- Operator

See Also	Syntax 1 Example	Syntax 2 Example

Used to find the difference between two numbers or to indicate the negative value of an operand.

Syntax 1

result = operand1 - operand2

Syntax 2

-number

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers.  The operands can be any numeric expression.

The data type of result is usually the same as that of the most precise operand.  The order of precision, from least to most precise, is Integer, Long, Single, Currency, Double.  The following are exceptions to this order:

When subtraction involves a Single and a Long, the data type of result is converted to a Double.

When the data type of result is a Variant of VarType 3 (Long), VarType 4 (Single), or  VarType 7 (Date) that overflows its legal range, result is converted to a Variant of VarType 5 (Double).

When the data type of result is a Variant of VarType 2 (Integer) that overflows its legal range, result is converted to a Variant of VarType 3 (Long).

If one or both operands are Null expressions, result is a Null.  If an operand is Empty (VarType 0), it is treated as if it were 0.

In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an operand.  As with Syntax 1, the operand can be any numeric constant, variable, expression, or any function that returns a number.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


- Operator Syntax 1 Example

The example subtracts a user-supplied number from 1000 and displays the result  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Result As Double	' Declare variables.

N = InputBox ("Enter a number.")	' Get a number.

Result = 1000 -N

MsgBox "1000 minus " & N & " is " & Result	' Display result.

End Sub


- Operator Syntax 2 Example

The example uses the - operator to indicate a negative value of a number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, MinusN As Double	' Declare variables.

N = InputBox("Enter a number")	' Get a number.

MinusN = -N	' Use negation operator.

MsgBox "Negative " & N & " is " & MinusN	' Display result.

End Sub


* Operator

See Also	Example

Used to multiply two numbers.

Syntax

result = operand1 * operand2

Remarks

The operands can be any numeric expression.

The data type of result is usually the same as that of the most precise operand.  The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency.  The following are exceptions to this order:

When multiplication involves a Single and a Long, the data type of result is converted to a Double.

When the data type of result is a Variant of VarType 3 (Long), VarType 4 (Single), or VarType 7 (Date) that overflows its legal range, result is converted to a Variant of VarType 5 (Double).

When the data type of result is a Variant of VarType 2 (Integer) that overflows its legal range, result is converted to a Variant of VarType 3 (Long).

If one or both operands are Null expressions, result is a Null.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


* Operator Example

The example determines tax on a user-supplied value using the * operator to multiply the user-supplied value by the tax rate of 15%.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Tax As Double 	' Declare variables.

N = InputBox("Enter a number.")	' Get tax rate.

Tax = .15 * N	' Calculate tax.

MsgBox "Tax is " & Tax	' Display results.

End Sub


/ Operator

See Also	Example

Used to divide two numbers and return a floating-point result.

Syntax

result = operand1 / operand2

Remarks

The operands can be any numeric expression.

The data type of result is usually a Double or a Variant of VarType 5 (Double).  The following are exceptions to this rule:

When both operands are Integer or Single expressions, result is a Single unless it overflows its legal range, in which case, result is a Double.

When both operands are Variant expressions of VarType 2 (Integer) or VarType 4 (Single), result is a Variant of VarType 4 (Single) unless it overflows its legal range, in which case, result is a Variant of VarType 5 (Double).

If one or both operands are Null expressions, result is a Null.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


/ Operator Example

The example divides 100,000 by 7 and returns 14,285.7142857143.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Result As Double	' Declare variable.

Result = 100000 / 7	' Divide numbers.

MsgBox "100000 divided by 7 is " & Result	' Display results.

End Sub


\ Operator

See Also	Example

Used to divide two numbers and return an integer result.

Syntax

result = operand1 \ operand2

Remarks

The operands can be any numeric expression.

Before division is performed, the operands are rounded to Integer or Long expressions.

Usually, the data type of result is an Integer, a Long, or a Variant of VarType 2 (Integer) or VarType 3 (Long) regardless of whether or not result is a whole number.  Any fractional portion is truncated.  However, if any operand is a Null, result is also a Null.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


\ Operator Example

The example divides 100,000 by 7 using integer division and returns 14,285.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Result As Double	' Declare variable.

Result = 100000 \ 7	' Divide numbers.

MsgBox "100000 divided by 7 is " & Result	' Display results.

End Sub


Mod Operator

See Also	Example

Divides two numbers and returns only the remainder.

Syntax

result = operand1 Mod operand2

Remarks

The modulus, or remainder, operator divides operand1 by operand2 (rounding floating-point numbers to integers) and returns only the remainder as result.  For example, in the expression  A = 19 Mod 6.7, A (which is result) equals 5.  The operands can be any numeric expression.

Usually, the data type of result is an Integer, a Long, or a Variant  of VarType 2 (Integer) or VarType 3 (Long).  However, result is a Null (VarType 1) if one or both operands are Null expressions.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


Mod Operator Example

The example uses the Mod operator to determine if a 4-digit year is a leap year.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestYr, LeapStatus	' Declare variables.

TestYr = InputBox("Enter a 4-digit year.")

If TestYr Mod 4 = 0 And TestYr Mod 100 = 0 Then	' Divisible by 4?

If TestYr Mod 400 = 0 Then	' Divisible by 400?

LeapStatus = " is a leap year."

Else

LeapStatus = " is a centesimal year, but not a leap year."

End If

ElseIf TestYr Mod 4 = 0 Then

LeapStatus = " is a leap year."

Else

LeapStatus = " is not a leap year."

End If

MsgBox TestYr & LeapStatus	' Display results.

End Sub


& Operator

See Also	Example

Used to force string concatenation of two operands.

Syntax

result = operand1 & operand2

Remarks

Whenever an operand is a number, it is converted to a Variant of VarType 8 (String).  The data type of result is String if both operands are String expressions; otherwise, result is a Variant of VarType 8 (String).  If both operands are Null (VarType 1), result is also Null.  However, if only one operand is Null, that operand will be treated as a zero-length string when concatenated with the other operand.  Any operand that is Empty (VarType 0) is also treated as a zero-length string.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


& Operator Example

The example uses the & operator to concatenate a numeric variable (Var1), a string literal containing a space, and a string variable (Var2) that contains "trombones".  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Var1, Var2	' Declare variables.

Var1 = 76

Var2 = "trombones"

MsgBox 76 & " " & Var2	' Concatenate and display.

End Sub


Comparison Operators

See Also	Example

Used to compare two expressions.

Syntax

result = expr1 operator expr2

Remarks

Comparison operators, also known as relational operators, compare two expressions.  The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator	Meaning	True if	False if	Null if
<	Less than	expr1 < expr2	expr1 >= expr2	expr1 or expr2 = Null
<=	Less than or equal to	expr1 <= expr2	expr1 > expr2	expr1 or expr2 = Null
>	Greater than	expr1 > expr2	expr1 <= expr2	expr1 or expr2 = Null
>=	Greater than or equal to	expr1 >= expr2	expr1 < expr2	expr1 or expr2 = Null
=	Equal to	expr1 = expr2	expr1 <> expr2	expr1 or expr2 = Null
<>	Not equal to	expr1 <> expr2	expr1 = expr2	expr1 or expr2 = Null
When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings.  The following table shows how the expressions are compared or what results when either expression is not a Variant:

If	Then
Both expressions are numeric data types (Integer, Long, Single, Double, or Currency)	Perform a numeric comparison.
Both expressions are String	Perform a string comparison.
One expression is a numeric data type and the other is a Variant of VarType 2-7 (a numeric data type) or VarType 8 (String) that can be converted to a number	Perform a numeric comparison.
One expression is a numeric data type and the other is a Variant of VarType 8 (String) that can't be converted to a number	A Type Mismatch error occurs.
One expression is a String and the other is a Variant of any VarType except Null	Perform a string comparison.
One expression is Empty and the other is a numeric data type	Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a String	Perform a string comparison, using a zero-length string as the Empty expression.
One expression is a numeric data type and the other is a Variant of VarType 8 (String)	A Type Mismatch error occurs.
If expr1 and expr2 are both Variant expressions, their VarType determines how they are compared.  The following table shows how the expressions are compared or what results from the comparison, depending on the VarType of the Variant:

If	Then
Both Variant expressions are of VarType 2-7 (numeric data types)	Perform a numeric comparison.
Both Variant expressions are of VarType 8 (String)	Perform a string comparison.
One Variant expression is of VarType 2-7 (a numeric data type) and the other is of VarType 8 (String)	The numeric expression is less than the String expression.
One Variant expression is Empty and the other is of VarType 2-7 (a numeric data type)	Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is of VarType 8 (String)	Perform a string comparison, using a zero-length string as the Empty expression.
Both Variant expressions are Empty	The expressions are equal.
Note	If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency.  This causes any fractional part of the Single or Double value less than 0.0001 to be lost and may cause two values to compare as equal when they are not.  Such a conversion can also cause an Overflow error if the magnitude of the Single or Double is too large.  When a Single is compared to a Double, the Double is rounded to the precision of the Single.


See Also

Arithmetic Operators

Concatenation Operators

Like Operator

Logical Operators

Operator Precedence

Option Compare Statement

Other Operators

VarType Function


Comparison Operators Example

The example shows a typical use of a comparison operator to evaluate the relationship between variables A and B.  An appropriate message is displayed depending on whether the A < B, A = B, or A > B.  The other comparison operators can be used in a similar way.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, Msg	' Declare variables.

A = InputBox("Enter a value for A.")	' Get first variable.

B = InputBox("Enter a value for B.")	' Get second variable.

If A < B Then	' Evaluate relationship.

Msg = "A is less than B."	' Create correct message.

ElseIf A = B Then

Msg = "A is equal to B."

Else

Msg = "A is greater than B."

End If

MsgBox Msg	' Display results.

End Sub


And Operator

See Also	Example

Used to perform a logical conjunction on two expressions.

Syntax

result = expr1 And expr2

Remarks

If, and only if, both expressions evaluate True, result is True.  If either expression evaluates False, result is False.  The following table illustrates how result is determined:

If expr1	And expr2	The result
is	is	is

True	True	True

True	False	False

True	Null	Null

False	True	False

False	False	False

False	Null	False

Null	True	Null

Null	False	False

Null	Null	Null

The And operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	0

0	1	0

1	0	0

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


And Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 6, both expressions evaluate True.  Because both expressions are True, the And expression is also True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 6	' Assign values.

If A > B And B > C Then	' Evaluate expressions.

Msg = "Both expressions are True."

Else

Msg = "One or both expressions are False."

End If

MsgBox Msg	' Display results.

End Sub


Eqv Operator

See Also	Example

Used to perform a logical equivalence on two expressions.

Syntax

result = expr1 Eqv expr2

Remarks

If either expression is a Null, result is also a Null.  When neither expression is a Null, result is determined according to the following table:

If expr1	And expr2	The result
is	is	is

True	True	True

True	False	False

False	True	False

False	False	True

The Eqv operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	1

0	1	0

1	0	0

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Eqv Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 6, both expressions evaluate True.  As a result, the Eqv expression also evaluates True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 6	' Assign values.

If A > B Eqv B > C Then	' Evaluate expressions.

Msg = "Both expressions are True or both are False."

Else

Msg = "One expression is True and one is False."

End If

MsgBox Msg	' Display results.

End Sub


Imp Operator

See Also	Example

Used to perform a logical implication on two expressions.

Syntax

result = expr1 Imp expr2

Remarks

The following table illustrates how result is determined:

If expr1	And expr2	The result
is	is	is

True	True	True

True	False	False

True	Null	Null

False	True	True

False	False	True

False	Null	True

Null	True	True

Null	False	Null

Null	Null	Null

The Imp operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	1

0	1	1

1	0	0

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Imp Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 6, both expressions evaluate True.  Because both are True, the Imp expression is also True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 6	' Assign values.

If A > B Imp B > C Then

Msg = "The left expression implies the right expression."

Else

Msg = "The left expression doesn't imply the right expression."

End If

MsgBox Msg	' Display results.

End Sub


Not Operator

See Also	Example

Used to perform logical negation on an expression.

Syntax

result = Not expr

Remarks

The following table illustrates how result is determined:

If expr is	Then result is

True	False

False	True

Null	Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following truth table:

Bit in expr	Bit in result

0	1

1	0

If an integer variable has the value 0 (False), the variable becomes -1 (True); if it has the value -1, it becomes 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence


Not Operator Example

The example displays a message that depends on the value of variables A and B, assuming neither variable is a Null.  If A = 10 and B = 8, the Not expression evaluates True because A is not equal to B.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, Msg	' Declare variables.

A = 10: B = 8	' Assign values.

If Not A = B Then	' Evaluate expression.

Msg = "A and B aren't equal."

Else

Msg = "A and B are equal."

End If

MsgBox Msg	' Display results.

End Sub


Or Operator

See Also	Example

Used to perform a logical disjunction on two expressions.

Syntax

result = expr1 Or expr2

Remarks

If either or both expressions evaluate True, result is True.  The following table illustrates how result is determined:

If expr1 is	And expr2	The result
is	is	is

True	True	True

True	False	True

True	Null	True

False	True	True

False	False	False

False	Null	Null

Null	True	True

Null	False	Null

Null	Null	Null

The Or operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	0

0	1	1

1	0	1

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Or Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 11,  the left expression is True and the right expression is False.  Because at least one comparison expression is True, the Or expression evaluates True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 11	' Assign values.

If A > B Or B > C Then	' Evaluate expressions.

Msg = "One or both comparison expressions are True."

Else

Msg = "Both comparison expressions are False."

End If

MsgBox Msg	' Display results.

End Sub


XOR Operator

See Also	Example

Used to perform a logical exclusion on two expressions.

Syntax

result = expr1 Xor expr2

Remarks

If only one of the expressions evaluates True, result is True.  If either expression is a Null result is also a Null.  When neither expression is a Null, result is determined according to the following table:

If expr1	And expr2	The result
is	is	is

True	True	False

True	False	True

False	True	True

False	False	False

The Xor operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	0

0	1	1

1	0	1

1	1	0


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Xor Operator Example

The example displays a message depending on the value of the variables A, B, and C, assuming that no variable is a Null.  If A = 6, B = 8, and C = 10, both expressions evaluate False.  Because both are False, the Xor expression is also False.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 6: B = 8: C = 10	' Assign values.

If A > B Xor B = C Then	' Evaluate expressions.

Msg = "Only one comparison expression is True, not both."

Else

Msg = "Both comparison expressions are True or both are False."

End If

MsgBox Msg	' Display results.

End Sub


Like Operator

See Also	Example

Used to compare two string expressions.

Syntax

result = expression Like pattern

Remarks

If expression matches pattern, result is True; if there is no match, result is False; and if either expression or pattern is a Null, result is also a Null.  The case sensitivity and character sort order of the Like operator depend on the setting of the Option Compare statement.  Unless otherwise specified, the default string-comparison method for each module is Option Compare Binary; that is, string comparisons are case-sensitive.

Built-in pattern matching provides a versatile tool for string comparisons.  The pattern-matching features allow you to use wildcard characters, such as those recognized by the operating system, to match strings.  The wildcard characters and what they match are shown in the following table:

Character(s)	Matches in
in pattern	expression

?	Any single character

*	Zero or more characters

#	Any single digit (0-9)

[charlist]	Any single character in charlist

[!charlist]	Any single character not in charlist

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in expression and can include almost any characters in the ANSI character set, including digits.  In fact, the special characters left bracket ([ ), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only by enclosing them in brackets.  The right bracket ( ]) cannot be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range.  For example, [A-Z] in pattern results in a match if the corresponding character position in expression contains any of the uppercase letters in the range A through Z.  Multiple ranges are included within the brackets without any delimiting.  For example, [a-zA-Z0-9]  matches any alphanumeric character.

Other important rules for pattern matching include the following:

An exclamation point (!) at the beginning of charlist means that a match is made if any character except the ones in charlist are found in expression.  When used outside brackets, the exclamation point matches itself.

The hyphen (-) can appear either at the beginning (after an exclamation mark if one is used) or at the end of charlist to match itself.  In any other location, the hyphen is used to identify a range of ANSI characters.

When a range of characters is specified, they must appear in ascending sort order (from lowest to highest).  [A-Z] is a valid pattern, but [Z-A] is not.

The character sequence [ ] is ignored; it is considered to be a zero-length string.

In some languages, there are special characters in the alphabet that actually represent two separate characters.  For example, several languages use the character "æ" to represent the characters "a" and "e" when they appear together.  The Like operator recognizes that the single special character and the two individual characters are equivalent.

When a language that uses one of these special characters is specified in the WIN.INI file (sLanguage), an occurrence of the special single character in either pattern or expression matches the equivalent 2-character sequence in the other string.  Similarly, a special single character in pattern enclosed in brackets (by itself, in a list, or in a range), matches the equivalent 2-character sequence in expression.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Instr Function

Logical Operators

Operator Precedence

Option Compare Statement

StrComp Function


Like Operator Examples

The following examples show how you can use Like to test expressions for different patterns.

Kind of matching	With this pattern	This expression returns True	This expression returns False
Multiple characters	a*a	"aa", "aBa", "aBBBa"	"aBC"
Special character	a[*]a	"a*a"	"aaa"
Multiple characters	ab*	"abcdefg", "abc"	"cab", "aab"
Single character	a?a	"aaa", "a3a", "aBa"	"aBBBa"
Single digit	a#a	"a0a", "a1a", "a2a"	"aaa", "a10a"
Range of characters	[a-z]	"f", "p", "j"	"2", "&"
Outside a range	[!a-z]	"9", "&", "%"	"b", "a"
Not a digit	[!0-9]	"A", "a", "&", "~"	"0", "1", "9"
Combined	a[!b-m]#	"An9", "az0", "a99"	"abc", "aj0"
Single special to double	[Æ]	"ae", "AE", "Æ"	"Ä", "A"


Is Operator

See Also	Example

Used to compare two object reference variables.

Syntax

result = objref1 Is objref2

Remarks

If objref1 and objref2 both refer to the same object result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways:

In the following example, A has been set to refer to the same object as B.

Set A = B

The following example makes A and B refer to the same object as C:

Set A = C

Set B = C


See Also

Set Statement


Is Operator Example

The example uses the Is operator to evaluate if two object reference variables refer to the same form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Dim A As New Form1	' Declare new instance of form.

Dim B As Form	' Declare new object reference.

Sub Form_Click ()

If A Is B Then	' Do they refer to same form?

Msg = "A and B refer to the same form."

Else

Msg = "A and B do not refer to the same form."

End If

MsgBox Msg	' Display message.

Set B = A	' Set B to same form as A.

If A Is B Then	' Check again.

Msg = "A and B refer to the same form."

Else

Msg = "A and B do not refer to the same form."

End If

MsgBox Msg	' Display message.

End Sub


Chr, Chr$ Functions

See Also	Example

Returns a one-character string whose ANSI  code is the argument.

Syntax

Chr[$](charcode)

Remarks

Chr returns a Variant; Chr$ returns a String.

The argument charcode is an integer between 0 and 255, inclusive.

Applications for Microsoft Windows use the ANSI character set.  ANSI character codes in the range 0 to 31, inclusive, are the same as the standard, nonprintable ASCII codes.  For example, Chr(10) returns a linefeed character.  It can be used to force a new line when message strings are formatted with MsgBox or InputBox.


See Also

Asc Function

Str, Str$ Functions


Chr, Chr$ Function Example

The example uses the Chr function to create a variable that will insert a newline character as well as a variable containing letters from A through Z.  Each time the line containing Chr is executed within the For...Next loop, another letter is appended to the Msg variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, J, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

For I = 1 to 2	' Set 2 iterations.

For J = Asc("A") To Asc("Z")	' From A through Z.

Msg = Msg & Chr(J)	' Create a string.

Next J

Msg = Msg & NL	' Insert newline.

Next I

MsgBox Msg	' Display results.

End Sub


Format, Format$ Function

See Also	Example

Formats a number, date, time, or string according to instructions contained in a format expression.

Syntax

Format[$](expression[, fmt] )

Remarks

Format returns a Variant; Format$ returns a String.

The Format[$] function has these parts:

Part	Description

expression	Numeric or string expression to be formatted.

fmt	Format expression [image] a string of  display-format characters that specify how the expression is to be displayed or the name of a commonly-used format that has been predefined in Visual Basic.  Different type format expressions (numeric, date/time, or string) cannot be mixed in a single fmt argument.

Note	If fmt is omitted or is zero-length and expression is a numeric expression, Format[$] provides the same functionality as the Str[$] function by converting the numeric value to the appropriate return data type.  Positive numbers converted to strings using Format[$] lack the leading space reserved for displaying the sign of the value, whereas those converted using Str[$] retain the leading space.

To format numbers, you can use the commonly-used formats that have been predefined in Visual Basic or you can create user-defined formats with standard characters that have special meaning when used in a format expression.

The following table shows the predefined numeric format names you can use and the meaning of each:

Format name	Description

General Number	Display the number as is, with no thousand separators.

Currency	Display number with thousand separator, if appropriate; display negative numbers enclosed in parentheses; display two digits to the right of the decimal separator.

Fixed	Display at least one digit to the left and two digits to the right of the decimal separator.

Standard	Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator.

Percent	Display number multiplied by 100 with a percent sign (%) appended to the right; display two digits to the right of the decimal separator.

Scientific	Use standard scientific notation.

Yes/No	Display No if number is 0, otherwise display Yes.

True/False	Display False if number is 0, otherwise display True.

On/Off	Display Off if number is 0, otherwise display On.

The following table shows the characters you can use to create user-defined number formats and the meaning of each:

Character	Meaning

Null string	Display the number with no formatting.

0	Digit placeholder.

Display a digit or a zero.  If there is a digit in the expression being formatted in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number being formatted has fewer digits than there are zeros (on either side of the decimal) in the format expression, leading or trailing zeros are displayed.  If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, the number is rounded to as many decimal places as there are zeros.  If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, the extra digits are displayed without modification.

#	Digit placeholder.

Display a digit or nothing.  If there is a digit in the expression being formatted in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.

.	Decimal placeholder.

The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator.  If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator.  If you want a leading zero to always be displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator instead.  The actual character used as a decimal placeholder in the formatted output depends on the Number Format specified in the International section of the Microsoft Windows Control Panel.  For some countries, a comma is used as the decimal separator.

%	Percentage placeholder.

The expression is multiplied by 100.  The percent character (%) is inserted in the position where it appears in the format string.

,	Thousand separator.

The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator.  Standard use of the thousand separator is specified if the format contains a comma surrounded by digit placeholders (0 or #).  Two adjacent commas or a comma immediately to the left of the decimal separator (whether or not a decimal is specified) means "scale the number by dividing it by 1000, rounding as needed."  You can scale large numbers using this technique.  For example, you can use the format string "##0,," to represent 100 million as 100.  Numbers smaller than 1 million are displayed as 0.  Two adjacent commas in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator.  The actual character used as the thousand separator in the formatted output depends on the Number Format specified in the International section of the Control Panel.  For some countries, a period is used as the thousand separator.

E- E+ e- e+	Scientific format.

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

:	Time separator.

The time separator separates hours, minutes, and seconds when time values are formatted.  The actual character used as the time separator depends on the Time Format specified in the International section of the Control Panel.

/	Date separator.

The date separator separates the day, month, and year when date values are formatted.  The actual character used as the date separator in the formatted output depends on Date Format specified in the International section of the Control Panel.

- + $ ( ) space	Display a literal character.

To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").

\	Display the next character in the format string.

Many characters in the format expression have a special meaning and can't be displayed as literal characters unless they are preceded by a backslash.  The backslash itself isn't displayed.  Using a backslash is the same as enclosing the next character in double quotation marks.  To display a backslash, use two backslashes (\\).

Examples of characters that can't be displayed as literal characters are the date- and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, and /:), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).

"ABC"	Display the string inside the double quotation marks.

To include a string in fmt from within Visual Basic, you must use Chr(34) to enclose the text (34 is the ANSI code for a double quotation mark).

*	Display the next character as the fill character.

Any empty space in a field is filled with the character following the asterisk.

Unless the fmt argument contains one of the predefined formats, a format expression for numbers can have from one to four sections separated by semicolons.

If you use	The result is

One section only	The format expression applies to all values.

Two sections	The first section applies to positive values and zeros, the second to negative values.

Three sections	The first section applies to positive values, the second to negative values, and the third to zeros.

Four sections	The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.

"$#,##0;($#,##0)"

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value.  For example, the following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero.

"$#,##0;;\Z\e\r\o"

Some sample format expressions for numbers are shown below. (These examples all assume that Country is set to United States in the International section of the Control Panel.)  The first column contains the format strings.  The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (fmt)	Positive 5	Negative 5	Decimal .5	Null
Null string	5	-5	0.5
0	5	-5	1
0.00	5.00	-5.00	0.50
#,##0	5	-5	1
#,##0.00;;;Nil	5.00	-5.00	0.50	Nil
$#,##0;($#,##0)	$5	($5)	$1
$#,##0.00;($#,##0.00)	$5.00	($5.00)	$0.50
0%	500%	-500%	50%
0.00%	500.00%	-500.00%	50.00%
0.00E+00	5.00E+00	-5.00E+00	5.00E-01
0.00E-00	5.00E00	-5.00E00	5.00E-01
Numbers can also be used to represent date and time information.  You can format date and time serial numbers using date and time formats or number formats because date/time serial numbers are stored as floating-point values.

To format dates and times, you can use either the commonly used formats that have been predefined in Visual Basic or create user-defined time formats using standard characters that have special meaning when used in a format expression.

The following table shows the predefined data format names you can use and the meaning of each:

Format Name	Description

General Date	Display a date and/or time.  For real numbers, display a date and time. (e.g. 4/3/93 05:34 PM); If there is no fractional part, display only a date (e.g. 4/3/93); if there is no integer part, display time only (e.g. 05:34 PM).

Long Date	Display a Long Date, as defined in the International section of the Control Panel.

Medium Date	Display a date in the same form as the Short Date, as defined in the International section of the Control Panel, except spell out the month abbreviation.

Short Date	Display a Short Date, as defined in the International section of the Control Panel.

Long Time	Display a Long Time, as defined in the International section of the Control Panel. Long Time includes hours, minutes, seconds.

Medium Time	Display time in 12-hour format using hours and minutes and the AM/PM designator.

Short Time	Display a time using the 24-hour format (e.g. 17:45)

The following table shows the characters you can use to create user-defined date/time formats and the meaning of each:

Character	Meaning

c	Display the date as ddddd and display the time as t t t t t, in that order.  Only date information is displayed if there is no fractional part to the date serial number; only time information is displayed if there is no integer portion.

d	Display the day as a number without a leading zero (1-31).

dd	Display the day as a number with a leading zero (01-31).

ddd	Display the day as an abbreviation (Sun-Sat).

dddd	Display the day as a full name (Sunday-Saturday).

ddddd	Display a date serial number as a complete date (including day, month, and year) formatted according to the Short Date setting in the International section of the Windows Control Panel.  The default Short Date format is m/d/yy.

dddddd	Display a date serial number as a complete date (including day, month, and year) formatted according to the Long Date setting in the International section of the Control Panel.  The default Long Date  format is mmmm dd, yyyy.

w	Display the day of the week as a number (1 for Sunday through 7 for Saturday.)

ww	Display the week of the year as a number (1-53).

m	Display the month as a number without a leading zero (1-12).  If m immediately follows h or hh, the minute rather than the month is displayed.

mm	Display the month as a number with a leading zero (01-12).  If m immediately follows h or hh, the minute rather than the month is displayed.

mmm	Display the month as an abbreviation (Jan-Dec).

mmmm	Display the month as a full month name (January-December).

q	Display the quarter of the year as a number (1-4).

y	Display the day of the year as a number (1-366).

yy	Display the year as a two-digit number (00-99).

yyyy	Display the year as a four-digit number (100-9999).

h	Display the hour as a number without leading zeros (0-23).

hh	Display the hour as a number with leading zeros (00-23).

n	Display the minute as a number without leading zeros (0-59).

nn	Display the minute as a number with leading zeros (00-59).

s	Display the second as a number without leading zeros (0-59).

ss	Display the second as a number with leading zeros (00-59).

t t t t t	Display a time serial number as a complete time (including hour, minute, and second) formatted using the time separator defined by theTime Format in the International section of the Control Panel.  A leading zero is displayed if the Leading Zero option is selected and the time is before 10:00 A.M. or P.M.  The default time format is h:mm:ss.

AM/PM	Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 PM.

am/pm	Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 PM.

A/P	Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 PM.

a/p	Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 PM.

AMPM	Use the 12-hour clock and display the contents of the 1159 string (s1159) in the WIN.INI file with any hour before noon; display the contents of the 2359 string (s2359) with any hour between noon and 11:59 PM.  AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as it exists in the WIN.INI file.  The default format is AM/PM.

The following are examples of user-defined date and time formats:

Format	Display

m/d/yy	12/7/58

d-mmmm-yy	7-December-58

d-mmmm	7 December

mmmm-yy	December 58

hh:mm AM/PM	08:50 PM

h:mm:ss a/p	8:50:35 p

h:mm	20:50

h:mm:ss	20:50:35

m/d/yy h:mm	12/7/58 20:50

Strings can also be formatted with Format[$].  A format expression for strings can have one section or two sections separated by a semicolon.

If you use	The result is

One section only	The format applies to all string data.

Two sections	The first section applies to string data, the second to Null values and zero-length strings.

You can use any of the following characters to create a format expression for strings:

Character	Meaning

@	Character placeholder.

Display a character or a space.  If there is a character in the string being formatted in the position where the @ appears in the format string, display it; otherwise, display a space in that position.  Placeholders are filled from right to left unless there is an ! character in the format string.  See below.

&	Character placeholder.

Display a character or nothing.  If there is a character in the string being formatted in the position where the & appears, display it; otherwise, display nothing.  Placeholders are filled from right to left unless there is an ! character in the format string.  See below.

<	Force lowercase.

All characters are displayed in lowercase format.

>	Force uppercase.

All characters are displayed in uppercase format.

!	Force placeholders to fill from left to right instead of right to left.


See Also

Str, Str$ Function


Format, Format$ Function Example

The example uses Format to format date and time values according to the setting of entries in the International section of the Microsoft Windows Control Panel.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "Today's date is " & Format(Now, "ddddd") & "." & NL

Msg = Msg & "The current time is " & Format(Now, "ttttt")

Msg = Msg & "."

MsgBox Msg	' Display date/time formatting.

End Sub


Hex, Hex$ Function

See Also	Example

Returns a string that represents the hexadecimal value of a decimal argument.

Syntax

Hex[$](number)

Remarks

Hex returns a Variant; Hex$ returns a String.

The argument number can be any numeric expression.  It is rounded to the nearest whole number before being evaluated.  An error occurs if number is a Variant of VarType 1 (Null).

If the argument is an Integer or a Variant of VarType 2 (Integer) or VarType 0 (Empty), up to four hexadecimal characters are returned; if the argument is any other numeric data type, or a Variant of any other type, up to eight hexadecimal characters are returned.

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


See Also

Oct, Oct$ Function


Hex, Hex$ Function Example

The example uses Hex to return the hexadecimal representation of a decimal number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Num	' Declare variables.

Num = InputBox("Enter a number.")	' Get user input.

Msg = Num & " decimal is &H"

Msg = Msg & Hex(Num) & " in hexadecimal notation."

MsgBox Msg	' Display results.

End Sub


InStr Function

See Also	Example

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

Syntax 1

InStr( [start,] strexpr1, strexpr2)

Syntax 2

 InStr(start, strexpr1, strexpr2 [, compare])

Remarks

The InStr function has these parts:

Part	Description

start	Numeric expression that sets the starting position for each search; start must be between 1 and approximately 65,535.  If start is omitted, the search of strexpr1 begins at the first character position.  The start argument is not optional if the compare argument is specified.

strexpr1	String expression being searched.

strexpr2	String expression being sought.

compare	Specifies the string-comparison method.  The argument compare must be 0 or 1.  If compare is 0, string comparison is case-sensitive;  so, for example, "M" doesn't match "m".  If compare is 1, string comparison is case-insensitive; so, for example, "M" matches "m".  If compare is omitted, the module default string-comparison method is used.  Unless you use Option Compare Text to change the default comparison method, the default is Option Compare Binary.

If strexpr2 is found within strexpr1, InStr returns the position at which the match was found.  If strexpr2 is zero-length, start is returned.  If start is greater than strexpr2, strexpr1 is zero-length, or strexpr2 can't be found, InStr returns 0.

If either string expression is Null, the function returns a Null.  If start or compare is Null, an error occurs.


See Also

Option Compare Statement


InStr Function Example

The example uses InStr to return the position of a character within a string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Alphabet, LetterNum, Msg, UsrInput	' Declare variables.

Alphabet ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Msg = "Please enter a single letter of the alphabet."

UsrInput = UCase(InputBox(Msg))	' Get user input.

If Len(UsrInput) Then

LetterNum = Instr(Alphabet, UsrInput)	' Get position.

If LetterNum <> 0 Then

Msg = "Your letter is number " & LetterNum

Msg = Msg  & " of " & Len(Alphabet) & "."

Else

Msg = "You didn't enter a letter of the alphabet!"

End If

Else

Msg = "You didn't enter anything."

End If

MsgBox Msg	' Display message.

End Sub


LCase, LCase$ Function

See Also	Example

Returns a string in which all letters of an argument have been converted to lowercase.

Syntax

LCase[$](strexpr)

Remarks

LCase returns a Variant; LCase$ returns a String.

The argument strexpr can be any string expression.  However, only LCase can accept a Variant of VarType 1 (Null ) as strexpr, in which case, a Null is returned.

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


See Also

UCase, UCase$ Function


LCase, LCase$ Function Example

The example uses LCase to return an all-lowercase version of the argument string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Lowercase, Msg, Uppercase	' Declare variables.

Uppercase = "ONCE UPON A TIME"	' String to convert.

Lowercase = LCase(UpperCase)	' Convert to lowercase.

Msg = "LCase converts """ & Uppercase & """ to """

Msg = Msg & Lowercase & "."""

MsgBox Msg	' Display message.

End Sub


Left, Left$ Function

See Also	Example

Returns the leftmost n characters of a string argument.

Syntax

Left[$](strexpr, n)

Remarks

Left returns a Variant; Left$ returns a String.

The Left[$] function has these parts:

Part	Description

strexpr	String expression from which the leftmost characters are returned.  This can be any string expression.  However, only Left can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

n	Long integer expression indicating how many characters to return.  It must be between 0 and approximately 65,535, inclusive.  If n is 0, the return value is a zero-length string.  If n is greater than or equal to the number of characters in strexpr, the entire string is returned.

To find the number of characters in strexpr, use Len(strexpr).


See Also

Len Function

Mid, Mid$ Function

Right, Right$ Function


Left, Left$ Function Example

The example uses the Left function to returns the first of two words input by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim LWord, Msg, RWord, SpcPos, UsrInp	' Declare variables.

Msg = "Enter two words separated by a space."

UsrInp = InputBox(Msg)	' Get user input.

SpcPos = InStr(1, UsrInp, " ")	' Find space.

If SpcPos Then

LWord = Left(UsrInp, SpcPos - 1)	' Get left word.

RWord = Right(UsrInp, Len(UsrInp) - SpcPos)	' Get right word.

Msg = "The first word you entered is """ & LWord

Msg = Msg & "." & """"  & " The second word is """

Msg = Msg & RWord & "." & """"

Else

Msg = "You didn't enter two words."

End If

MsgBox Msg	' Display message.

End Sub


Len Function

See Also	Example

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

Syntax 1

Len(strexpr)

Syntax 2

Len(variablename)

Remarks

If you use the first syntax, Len returns the number of characters in the argument strexpr.

If you use the second syntax, Len returns the number of bytes required to store a variable of the given data type.  If variablename is a Variant, Len always returns the number of bytes required to store the Variant data as a String, regardless of the VarType.

Because Len works with user-defined data types as well as fundamental Visual Basic data types, the second syntax is particularly useful for determining record size when you are performing file input/output with random-access files.  However, if a user-defined data type contains Variant or variable-length String elements, Len may not be able to properly determine the actual number of storage bytes required.

If the argument to Len is Null, the function returns a Null.


See Also

InStr Function


Len Function Example

The example shows how Len can be used to return the number of bytes needed to store each fundamental Visual Basic data type.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A As Integer, B As Long	' Declare variables.

Dim C As Single, D As Double

Dim E As Currency, F As Variant

Dim Msg, NL

NL = Chr(10)	' Define newline.

A% = 1	' Integer

B& = A%	' Long integer

C! = B&	' Single-precision, floating-point

D# = C!	' Double-precision, floating-point

E@ = D#	' Currency

F = E@	' Variant

Msg = "Integer values are stored in " & Len(A%) & " bytes."

Msg = Msg & NL & "Long integer values are stored in "

Msg = Msg & Len(B&) & " bytes." & NL

Msg = Msg & "Single-precision values are stored in "

Msg = Msg & Len(C!) & " bytes." & NL & "Double-precision "

Msg = Msg & "values are stored in " & Len(D#) & " bytes."

Msg = Msg & NL & "Currency values are stored in " & Len(E@)

Msg = Msg & " bytes." & NL & "This Variant requires " & Len(F)

Msg = Msg & " bytes to store it as a string." & NL

Msg = Msg &  "This message contains "

Msg = Msg & "more than " & Len(Msg) & " characters."

MsgBox Msg	' Display message.

End Sub


LSet Statement

See Also	Example

Left aligns a string within the space of a string variable or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax 1

LSet stringvar = stringexpr

Syntax 2

LSet variable1 = variable2

Remarks

The LSet statement has these parts:

Part	Description

stringvar	Name of a String variable.

stringexpr	String expression to be left aligned within stringvar.

variable1	Name of the user-defined type variable being copied to.

variable2	Name of the user-defined type variable being copied from.

If stringexpr is shorter than stringvar, LSet left aligns stringexpr within stringvar.  LSet replaces any leftover characters in stringvar with spaces.

If stringexpr is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.  Characters beyond the length of stringvar are truncated from the right.

Use LSet with Syntax 2 to assign one user-defined type variable to another.  The following example copies the contents of RecTwo (a user-defined type variable) to RecOne (a variable of another user-defined type):

Type TwoString

StrFld As String * 2

End Type

Type ThreeString

StrFld As String * 3

End Type

Dim RecOne As TwoString, RecTwo As ThreeString

LSet RecOne = RecTwo

Because RecOne is 2 bytes long, only 2 bytes are copied from RecTwo.  LSet copies only the number of bytes in the shorter of the two user-defined type variables.

You can't use LSet to copy variables of different user-defined types if either contains a variable-length string or a Variant.


See Also

RSet Statement


LSet Statement Example

The example uses LSet to left align text in a 40-character String variable).  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, OldFont, TmpStr	' Declare variables.

NL = Chr(10)	' Define newline.

OldFont = FontName	' Save old font.

FontName = "Courier"	' Use monospaced font

TmpStr = String(40, "*")	' Create 40-character string.

Msg = "Here are two strings that have been right"

Msg = Msg & NL & "and left justified in a " & Len(TmpStr)

Msg = Msg & "-character string." & NL & TmpStr & NL

RSet TmpStr = "Right->"	' Right justify.

Msg = Msg & TmpStr & NL

LSet TmpStr = "<-Left"	' Left justify.

Msg = Msg & TmpStr & NL

Print Msg	' Display message.

FontName = OldFont	' Restore original font.

End Sub


LTrim, LTrim$, RTrim, RTrim$, Trim, Trim$ Functions

Example

Returns a copy of a string with leading (leftmost), trailing (rightmost), or both leading and trailing spaces removed.

Syntax

[L | R]Trim[$](stringexpr)

Remarks

LTrim[$] removes leading spaces from a string; RTrim[$] removes trailing spaces.  Trim[$] removes leading and trailing spaces.

LTrim, RTrim, and Trim each return a Variant; LTrim$, RTrim$, and Trim$ each return a String.

The stringexpr argument can be any string expression.  However, only LTrim, RTrim, and Trim can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.


LTrim, LTrim$, RTrim, RTrim$, Trim, Trim$ Functions Example

The example uses LTrim and RTrim, to strip leading and trailing spaces from a string variable.  The stripping of both leading and trailing spaces can be more efficiently done using the Trim function.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, TestStr, TestStr1	' Declare variables.

NL = Chr(10)	' Define newline.

TestStr = "  Test String  "

TestStr1 = LTrim(RTrim(TestStr))	' Strip spaces left and right.

Msg = "The original TestStr """ & TestStr & """ was "

Msg = Msg & Len(TestStr) & " characters long. There were two "

Msg = Msg & "leading spaces and two trailing spaces." & NL & NL

Msg = Msg & "The TestStr returned after stripping the spaces "

Msg = Msg & "is """ & TestStr1 & """ and it contains only "

Msg = Msg & Len(TestStr1) & " characters."

MsgBox Msg	' Display message.

End Sub


Mid, Mid$ Functions

See Also	Example

Returns a string that is part of some other string.

Syntax

Mid[$](stringexpr, start[, length])

Remarks

Mid returns a Variant; Mid$ returns a String.

The Mid[$] function has these parts:

Part	Description

stringexpr	String expression from which another string is created.  This can be any string expression.  However, only Mid can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

start	Long expression that indicates the character position in stringexpr at which the part to be taken begins.

length	Long expression that indicates the number of characters to return.

The arguments start and length must be between 1 and approximately 65,535, inclusive.  If length is omitted or if there are fewer than length characters in the text (including the character at start), the Mid[$] function returns all characters from the start position to the end of the string.

If start is greater than the number of characters in stringexpr, Mid[$] returns a zero-length string.

Use the Len function to find the number of characters in stringexpr.


See Also

Left, Left$ Function

Len Function

Mid, Mid$ Statement

Right, Right$ Function


Mid, Mid$ Function Example

The example uses the Mid function to return the middle word from a variable containing three words.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim MidWord, Msg, TstStr, SpcPos1, SpcPos2	' Declare variables.

TstStr = "Mid Function Demo"	' Create text string.

SpcPos1 = InStr(1, TstStr, " ")	' Find first space.

SpcPos2 = InStr(SpcPos1 + 1, TstStr, " ")	' Find next space.

WordLen = (SpcPos2 - SpcPos1) - 1	' Calculate 2nd word length.

MidWord = Mid(TstStr, SpcPos1 + 1, WordLen)	' Return 2nd word.

Msg = "The word in the middle of Title is """ & MidWord & """"

MsgBox Msg, 0, TstStr	' Display message.

End Sub


Mid$ Statement

See Also	Example

Replaces part of a string with another string.

Syntax

Mid[$](stringvar, start [, length])  =  stringexpr

Remarks

There is no functional difference between Mid and Mid$.  The Mid[$] statement has these parts:

Part	Description

stringvar	String or Variant (VarType 8) variable to modify.

start	Character position in stringvar where the replacement text begins.

length	Number of characters to replace.

stringexpr	String expression that replaces part of stringvar.

The arguments start and length must be between 1 and approximately 65,535, inclusive.  The argument stringvar must be a variable, but stringexpr can be any string expression.

The optional argument length refers to the number of characters from the argument stringexpr that are used in the replacement.  If length is omitted, all of stringexpr is used.  Whether or not length is included, the number of characters replaced is always less than or equal to the number of characters in stringvar.


See Also

Mid, Mid$ Function


Mid, Mid$ Statement Example

The example uses the Mid$ statement to substitute "dog" for  "fox" within a string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Head1, Head2, Orig, Start, Test	' Declare variables.

Dim NL, TB

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

Head1 = "Original string:"

Head2 = "Replacement string:"

Orig = "The quick brown fox jumped over the wall."

Test = Orig	' Make a copy of Original

Start = Instr(Test,"fox")	' Find where "fox" begins.

Mid(Test, Start, 3) = "dog"	' Replace "fox" with "dog".

Msg = Head1 & NL & TB & Orig

Msg = Msg & NL & Head2 & NL & TB & Test

MsgBox Msg	' Display message

End Sub


Oct, Oct$ Functions

See Also	Example

Returns text that represents the octal value of the decimal argument.

Syntax

Oct[$](number)

Remarks

Oct returns a Variant; Oct$ returns a String.

The argument number can be any numeric expression.  It is rounded to the nearest whole number before being evaluated.  An error occurs if number is a Variant of VarType 1 (Null).

If the argument is an Integer or a Variant of VarType 2 (Integer) or VarType 0 (Empty), up to six octal characters are returned; if the argument is any other numeric data type or a Variant of any other type, up to 11 octal characters are returned.

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


See Also

Hex, Hex$ Function


Oct, Oct$ Function Example

The example uses Oct to return the octal representation of a decimal number. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Num	' Declare variables.

Num = InputBox("Enter a number.")	' Get user input.

Msg = Num & " decimal is &O"

Msg = Msg & Oct(Num) & " in octal notation."

MsgBox Msg	' Display results.

End Sub


Right, Right$ Functions

See Also	Example

Returns the rightmost n characters of a string argument.

Syntax

Right[$](stringexpr, n)

Remarks

Right returns a Variant; Right$ returns a String.

The Right[$] function has these parts:

Part	Description

strexpr	String expression from which the rightmost characters are returned.  This can be any string expression.  However, only Right can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

n	Long integer expression indicating how many characters to return.  It must be between 0 and approximately 65,535, inclusive.  If n is 0, the return value is a zero-length string.  If n is greater than or equal to the number of characters in strexpr, the entire string is returned.

To find the number of characters in stringexpr, use Len(stringexpr).


See Also

Left, Left$ Function

Len Function

Mid, Mid$ Function


Right, Right$ Function Example

The example uses the Right function to return the second of two words input by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim LWord, Msg, RWord, SpcPos, UsrInp	' Declare variables.

Msg = "Enter two words separated by a space."

UsrInp = InputBox(Msg)	' Get user input.

SpcPos = InStr(1, UsrInp, " ")	' Find space.

If SpcPos Then

LWord = Left(UsrInp, SpcPos - 1)	' Get left word.

RWord = Right(UsrInp, Len(UsrInp) - SpcPos)	' Get right word.

Msg = "The first word you entered is """ & LWord

Msg = Msg & "." & """"  & " The second word is """

Msg = Msg & RWord & "." & """"

Else

Msg = "You didn't enter two words."

End If

MsgBox Msg	' Display message.

End Sub


RSet Statement

See Also	Example

Right aligns a string within the space of a string variable.

Syntax

RSet stringvar = stringexpr

Remarks

The RSet statement has these parts:

Part	Description

stringvar	Name of a String variable.

stringexpr	String expression to be right aligned within stringvar.

If stringexpr is shorter than stringvar, RSet right aligns stringexpr within stringvar.  RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

If stringexpr is longer than stringvar, RSet places only the leftmost characters, up to the length of stringvar, in stringvar.  Characters beyond the length of stringvar are truncated from the right.

You can't use RSet to assign variables of one user-defined type to those of another.


See Also

LSet Statement


RSet Statement Example

The example uses RSet to right align text in a 40-character String variable).  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, OldFont, TmpStr	' Declare variables.

NL = Chr(10)	' Define newline.

OldFont = FontName	' Save old font.

FontName = "Courier"	' Use monospaced font.

TmpStr = String(40, "*")	' Create 40-character string.

Msg = "Here are two strings that have been right"

Msg = Msg & NL & "and left justified in a " & Len(TmpStr)

Msg = Msg & "-character string." & NL & TmpStr & NL

RSet TmpStr = "Right->"	' Right justify.

Msg = Msg & TmpStr & NL

LSet TmpStr = "<-Left"	' Left justify.

Msg = Msg & TmpStr & NL

Print Msg	' Display message.

FontName = OldFont	' Restore original font.

End Sub


Space, Space$ Functions

See Also	Example

Returns a string consisting of a specified number of spaces.

Syntax

Space[$](number)

Remarks

Space returns a Variant; Space$ returns a String.

The argument number specifies the number of spaces you want in the string.  It can be of any numeric data type but is rounded to a Long and must be between 0 and approximately 65,535, inclusive.


See Also

Spc Function

String, String$ Functions


Space, Space$ Function Example

The example uses Space to create a variable containing 10 spaces.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Pad, UsrInp	' Declare variables.

UsrInp = InputBox("Enter your first name")	' Get user input.

Pad = Space(10)	' Create 10-space pad.

Msg = "Notice the 10-space pad between the first part of this "

Msg = Msg & "and your name.  " & Pad & UsrInp

MsgBox Msg	' Display message.

End Sub


Str, Str$ Functions

See Also	Example

Return a string representation of the value of a numeric expression.

Syntax

Str[$](number)

Remarks

Str returns a Variant; Str$ returns a String.

Use Str[$] to convert simple numeric values to strings.  Use the Format[$] function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats.

When numbers are converted to text, a leading space is always reserved for the sign of number.  If number is positive, the string returned by Str[$] contains a leading space and the plus sign is implied.  Format[$] doesn't include a leading space.

The Val function complements Str[$] by returning the numeric value of a string.


See Also

Format, Format$ Function

Val Function


Str, Str$ Function Example

The example uses Str to return a string representation of the values contained in two variables.  Note that because the numbers are positive, a space for the implied plus sign precedes the first string character.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg	' Declare variables.

Randomize	' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)	' Generate first die value.

Dice2 = Int(6 * Rnd + 1)	' Generate second die value.

Msg = "You rolled a" & Str(Dice1)

Msg = Msg & " and a" & Str(Dice2)

Msg = Msg & " for a total of"

Msg = Msg & Str(Dice1 + Dice2) & "."

MsgBox Msg	' Display message.

End Sub


StrComp Function

See Also	Example

Returns a Variant that indicates the result of the comparison of two string arguments.

Syntax

StrComp( stringexpr1, stringexpr2 [, compare])

Remarks

The StrComp function has these parts:

Part	Description

stringexpr1	Any string expression.

stringexpr2	Any string expression.

compare	Specifies the string-comparison method.  The argument compare must be 0 or 1.  If compare is 0, string comparison is case-sensitive;  so, for example, "M" doesn't match "m".  If  compare is 1, string comparison is case-insensitive;  so, for example, "M" matches "m".  If compare is omitted, the module default string-comparison method is used.  Unless you use Option Compare Text to change the default comparison method, the default is Option Compare Binary.

The StrComp function returns a Variant that indicates the relationship between the string expressions.  Regardless of underlying data type (Variant or String), each string expression argument is converted to a Variant and then both arguments are compared.  The following table illustrates the possible StrComp return values:

Return Value	Condition

-1	stringexpr1 < stringexpr2

0	stringexpr1 = stringexpr2

1	stringexpr1 > stringexpr2

Null	stringexpr1 = Null or stringexpr2 = Null


See Also

Option Compare Statement


StrComp Function Example

The example uses StrComp to compare two variables.  If the default comparison method is in effect (Option Compare Binary) this code will indicate that Var1 is less than Var2.  However, if Option Compare Text is in effect, the comparison will indicate that the variables are equal.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Cmp, Msg, Var1, Var2	' Declare variables.

Var1 = "ABCD": Var2 = "abcd"	' Define variables.

Cmp = StrComp(Var1, Var2)	' Compare variables.

Select Case Cmp

Case -1

Msg = "Var1 is less than Var2."

Case 0

Msg = "Var1 is equal to Var2."

Case 1

Msg = "Var1 is greater than Var2."

End Select

MsgBox Msg	' Display message.

End Sub


String, String$ Functions

See Also	Example

Returns a string whose characters all have a given ANSI code or are all the first character of a string expression.

Syntax 1

String[$](number, charcode)

Syntax 2

String[$](number, string)

Remarks

String returns a Variant; String$ returns a String.

Use String[$] to create a string that consists of one character repeated over and over.

The String[$] function has these parts:

Part	Description

number	Numeric expression indicating the length of the returned string.  It must be between 0 and approximately 65,535.

charcode	ANSI code of the character to use to build the return string.  It is a numeric expression that evaluates to an Integer between 0 and 255, inclusive.

string	String expression whose first character is used to build the return string.

If the second argument (charcode or string) in either syntax is a Variant, the underlying data type determines how String[$] uses that argument.  If the argument is a Variant of VarType 8 (String), String[$] uses the first character to create the return string.  If the argument is a Variant of VarType 2-7 (any numeric type), String[$] uses the numeric value as the ANSI code for the character used to create the return String.  A Variant of VarType 1 (Null) produces an error.  To convert numeric values greater than 255 to an ANSI code between 0 and 255, String [$] uses the remainder after the value is divided by 256 (argument Mod 256).


See Also

ANSI Character Set

Space, Space$ Function


String, String$ Function Example

The example uses the String function to return a Variant consisting of 10 asterisks.  The ANSI code of the asterisk character is 42.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "This demo generates two strings of 10 asterisks.  Both "

Msg = Msg & "forms of String[$] syntax are illustrated.  " & NL

Msg = Msg & NL & "Here is the 1st: " & String(10, "*") & NL

Msg = Msg & "Here is the 2nd: " & String(10, 42)

MsgBox Msg	' Display message.

End Sub


UCase, UCase$ Functions

See Also	Example

Returns a string in which all letters of an argument have been converted to uppercase.

Syntax

UCase[$](stringexpr)

Remarks

UCase returns a Variant; UCase$ returns a String.

The argument stringexpr can be any string expression.  However, only UCase can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

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


See Also

LCase, LCase$ Function


UCase, UCase$ Function Example

The example uses UCase to return an all-uppercase version of the argument string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Lowercase, Msg, Uppercase	' Declare variables.

Lowercase = "once upon a time"	' String to convert.

Uppercase = UCase(Lowercase)	' Convert to uppercase.

Msg = "UCase converts """ & Lowercase & """ to """

Msg = Msg & Uppercase & "."""

MsgBox Msg	' Display message.

End Sub


'|' is a Read-Only file
<Filename> is a Read-Only file

You asked to save to a file that is read-only.  Readonly files are shown in the Project window with a red lock in the lower-left corner. You cannot save to readonly files. Use Save As instead.


An expression must be selected

A variable, expression, or property reference must be selected before using the Instant Watch command. Note: While in the Code window, it is also possible to place the cursor on the variable and then invoke the Instant Watch command.


An undo error has occurred. Further undo is unavailable

The Undo / Redo mechanism is unable to perform the requested undo or redo operation.  Both undo and redo buffers have been flushed; therefore, old edits cannot be undone or redone.  Edits performed after the message will be recorded and can be undone or redone.


Can't have more than one window List menu

You clicked the Window List check box for more than one menu item and then clicked OK to close the dialog.  For a particular form, only one menu can have the Window List check box checked.  This is done through the Menu Design window.


Can't set formal parameter

You can't use a procedure's formal parameter as the destination of a Set statement.


Cannot destroy active form instance

Error 95

Form instances created with the New keyword cannot be unloaded from the Debug window if there are halted event procedures for that form instance.


Circular references between modules

A cycle between modules prevents Visual Basic from being able to compile your program.   Restructure your code to eliminate the cycle.  Example of a cycle:

Module 1:	Module 2:

  dim  a as t2	type t2

  type t1	x as integer

x as integer	end type

  end type	dim b as t1


Controls without the Align property cannot be placed directly on the MDI form

You tried to double-click on a control to have it placed on the MDI form and the control doesn't support the standard property Align.  A picture box is the only standard control that can be placed on an MDI form.  When an MDI child form is maximized within the parent MDI form, it will not cover any picture boxes.

An example of good usage: Create new MDIform and double-click on picture box

An example of bad usage: Create new MDIform and double-click on text box


Duplicate Option statement

You've defined more than one "Option Compare" or "Option Explicit" statement in your module. Remove the one you don't want.


Duplicate procedure name

You have defined (or are attempting to define) more than one version of a procedure with the same name.  Rename one of the procedures.  Ensure that duplicate Declare statements for the same procedure have the same Alias clause.


For index in use
For index variable already in use

You have nested For loops that are using the same index. For example:

For i% = 1 to 10

For i% = 1 to 20

print i%

next i%

next i%

Change the index on one of the loops to another variable name.


For loop not initialized

Error 92

You've jumped into the middle of a For loop with a variant index. Do not place labels inside a For loop.


Global definition invalid inside form module

You can't have a Type ... End Type block, Global statement, or Global Const statement in a form module.  Data in a form module cannot be referenced by other modules.  Move data that must be global to a non-forms module.


Illegal Watch expression

You tried to enter a watch expression containing one of the following intrinsic functions: LoadPicture, InputBox, MsgBox, DoEvents, Shell, or Input.


Invalid object reference

An object is required here, and you have specified something that is not an object.

Set x% = 1, for example.  Or, you have specified an object where one is not allowed.


Invalid pattern string

Error 93

The pattern string specified in the Like operator of the Search operation is invalid.  A common mistake is an invalid character-list expression, such as [a-b  (missing the right bracket).


Invalid use of Null

Error 94

You are trying to obtain the value of a Variant variable or an expression that is Null.  Null is normally used to signal an error condition, or to indicate that a data item contains no data.


Method not applicable for this object

You are attempting to invoke a method on an object that doesn't support this method.

For example  Clipboard.Print is invalid because the Clipboard object does not support the print method.


New not allowed on this type

Auto-construction is not supported on this type of object.  You can't use the New keyword on it.

Example of good usage: Dim x as new form1

Example of bad usage: Dim x as new Textbox1

In the base product: the keyword New can be used only on specific instances of form types (Form1, etc.).  It cannot be used on the general class form or MDIform or on any control types.  In the Visual Basic Professional Edition, there are some vt objects for which New is allowed.


Object does not have a value

You are trying to get the value of an object that doesn't have a value.   You may be trying to use an object in a place where objects of that type are not allowed or you may have left off a property or control suffix.


Object variable not set

Error 91

You are attempting to use a non-autoinstalling object variable that is not yet pointing to a valid object, or one that has been set to null.


Separator may not be the window List menu

The window menu has to be a menu item that can support being a popup menu (i.e., one that can have subitems).  A separator cannot have subitems.


Type too large

The sum of sizes of the elements of a user-defined type exceeds 64K.  You must reduce the size of this type.  Consider replacing fixed-length strings with variable-length strings.


User functions not allowed in Watch expressions

You have placed a user function in a watch expression. You cannot reference one of your Functions in a watch expression.


Valid Range: [1..32]
Valid range: [1...32]

You attempted to set the Tab Stop Width beyond the permitted range.   A number between 1 and 32 (inclusive) is acceptable for this field.


Valid Range:[24..1188]
Valid range: [24...1188]

You attempted to set the Grid Width or Grid Height beyond the permitted range.   A number between 24 and 1188  (inclusive) is acceptable for this field.


Variable not defined

You've used an Option Explicit statement to require the explicit declaration of variables, and you've used a variable without declaring it. This option protects your application from undeclared variables.


Watch expression too long, expression truncated

Watch expressions are limited to 64 characters.  If you enter a watch expression that expands to greater than 64 characters,  then the expression can still be evaluated, but it is truncated to 64 characters if you attempt to edit the expression.


Errors during load. Refer to "|' for details
Errors during load. Refer to <log file> for details

Something unexpected appeared in the ASCII form file.  Visual Basic has created a log file to provide more detail about the errors.  You should examine the log file to determine the severity of the problem. Sometimes the encountered errors are benign  (e.g., "Version number missing or invalid...") and you can safely ignore them.  Other times, however, the errors could cause the form to not run as expected. (e.g., "Class MyClass in control  MyControl was not a loaded control class")


String value to long to process; form load aborted
String value too long to process; form load aborted

There was a string embedded in the form being loaded.  It was too long to process.


Version number missing or invalid; Visual Basic 2.0 assumed.

Either the version signature was not found or the specified version is not recognized.  Make sure that the first non-blank, non-comment line in the ASCII form reads "Version 2.00."


Line |1: The file |2 could not be loaded.
Line <line number>: The file <filename> could not be loaded.

Syntax errors prevent Visual Basic from parsing and loading, or form name conflicts prevent loading of an ASCII form.  The form will not be loaded and the form name will not be displayed in the Project window.

Make sure that the file that caused this error is a valid ASCII form in the correct format and that there are no conflicts among the different forms in the project.  The correct ASCII form format is:

Version 2.00
Begin {Form | MdiForm} <formname>
prop = value
prop = value
[...]
Begin <control class> <control name>
prop = value
[...]
Begin ...
[...]
End
End
End


'|' could not be loaded
'<item>' could not be loaded

Syntax errors prevent Visual Basic from parsing and loading, or form name conflicts prevent loading of an ASCII form.  The form will not be loaded and the form name will not be displayed in the Project window.

Make sure that the file that caused this error is a valid ASCII form in the correct format, and that there are no conflicts among the different forms in the project.  The correct ASCII form format is:

Version 2.00
Begin {Form | MdiForm} <formname>
prop = value
prop = value
[...]
Begin <control class> <control name>
prop = value
[...]
Begin ...
[...]
End
End
End


Line too long

A line of Visual Basic code cannot contain more than 1023 characters.  Break the line into individual statements or assign some expressions to intermediate variables.


Identifier too long

Identifiers cannot be more than 40 characters long.


Invalid identifier

The names of variables, procedures, forms, and controls cannot be reserved words, must start with a letter, and can be no longer than 40 characters [image] including letters, numbers, and underscores (_).

To reference an object that conflicts with a reserved word, enclose the reference in square brackets.


Identifier can't end with type-declaration character

The following cannot contain a type declaration character:

A Sub procedure name

An identifier declared with a data type using an As clause

The name of a user-defined type

The name of any object or property


Invalid number

A number is inappropriate for its context.

Possible causes:

A type declaration character is used with an incompatible number.  For example, 10.2% is invalid because an Integer type (%) cannot have a fractional part.

A fixed-length string is declared to have length zero.  For example,

Dim X As String 0

will produce this message.


Invalid constant declaration

Possible causes:

An invalid expression has been used to assign a value to a symbolic constant.  Valid expressions are described in the Const topic.

An undefined constant is referred to.  For example, if "D" is not defined, the following produces this error:

Const C = D

Dim X As String * 0


Expected:
Expected: <various>

An expected piece of code was not found.  The error is usually located to the left of the selected item.


Syntax error

Visual Basic can't determine what action to take.

Possible causes:

A keyword or argument is misspelled.

Punctuation is incorrect.

A Sub procedure is not defined.


Invalid outside of Sub or Function

The statement must occur within a Sub or Function procedure.  Executable statements, Static, and ReDim can be used only in a Sub or Function procedure.  In the Declarations section of a form or module you can use only comments and the declarative statements Declare, Deftype, Dim, Option, Global, Global Const, and Type.


Invalid in Sub or Function

The statement cannot occur in a Sub or Function procedure.  The statements Declare, Deftype, Global, Global Const, Option, and Type are not allowed in procedures.


Statement cannot precede Sub/Function definition

Only comments are allowed before a Sub or Function statement.


Sub/Function without End Sub/Function

The terminating statement is missing from the procedure.


Element not defined

An element of a user-defined type is referred to but not defined.  Check the defining Type statement in the application modules to find the element names for this data type.


Type not defined

A variable or argument was declared with an undefined data type.  Use the Type statement in a module to define a new data type.


Must be first statement on the line

Sub and Function must always be the first statement on any line in which they appear.  Additionally, End If, Else (only when used in a block If structure), and ElseIf can be used only when they are the first statements on a line.


End Sub or End Function must be last statement

Nothing can appear in a Code window below the statement terminating the procedure.  Move all lines below the End Sub or End Function statement into the procedure.


End Type without Type

An End Type statement does not have a matching Type statement.


Statement invalid in Type block

Only comments and the As datatype clause are allowed within a Type...End Type pair.


Invalid Declare for procedure
Invalid Declare for Visual Basic procedure

You tried to declare a Visual Basic function in a form.  You can declare a Visual Basic function only in a module, and then only if you want to declare a function that has no arguments so it can be invoked without parentheses.  If this is the case, declare it in the Declarations section of each module where a reference to the function occurs.  You can then refer to the function without parentheses from each module where it is declared.  However, you still need to include the parentheses if you refer to the function from a form or from a module that does not contain an explicit declaration for the function.  Declarations for Visual Basic Sub procedures are not allowed.


Operation requires disk

You are attempting to load from, or save to, a non-disk device such as the printer, keyboard, or communications port.


Breakpoint not allowed on this line

You cannot set a breakpoint in any of the following:

Declarations section of a form or module

Case clause

End Select statement

Blank line


Label definition invalid in Immediate window
Label definition invalid in Immediate pane

You cannot enter a line label or line number in the Immediate pane. A label is a string followed by a colon or a line number.  A number on a line by itself is interpreted as a label.


Invalid in Immediate window
Invalid in Immediate pane

Possible causes:

Declarative statements such as Const, Declare, Deftype, Dim, Function, Global, Option Base, Option Explicit, Option Compare, ReDim, Static, Sub, and Type are not allowed in the Immediate pane.

Multiline statements, such as a block If, are not allowed in the Immediate pane.

You tried to execute some code in the Immediate pane that invalidates the current state of your program and requires reinitializing the program.


File previously loaded

You tried to load a file that has the same name as a loaded file or module.


Tried to load file with duplicate procedure definition
Tried to load file with duplicate procedure definition: <procedure name>

You tried to load a module that contains one or more procedure names already used in the existing procedures.  Use the Find command on the Edit menu to find the duplicated procedure names.


Can't load module; invalid format

You tried to load a module that has an incompatible format or is damaged.


Use Static or ReDim to dimension arrays in this procedure

You are trying to use Dim to create a fixed array (an array having a specific number of elements) at the procedure level.  To create a fixed array, use Dim at the module level or Static at the procedure level.  You may also choose to create a dynamic array at the procedure level using ReDim.

Arrays created with Static are persistent arrays whose values are kept in memory after the procedure is finished running.  Procedure-level dynamic arrays are released automatically at procedure exit.


Wrong number of dimensions

You referred to an array with a different number of dimensions than it actually has -- for example, referring to an array as X(2,4), an array with two dimensions, when it has been defined as Dim X(5), a one-dimensional array.


End If without block If

An End If statement is used without a corresponding If statement.  Check other control structures within the If...End If structure and verify that they are correctly matched.  For example, a While without a matching Wend inside the If...End If structure will generate this error.

Also check that the block If is correctly formatted.


Block If without End If

An If statement is used without a corresponding End If statement.  Check if there is an incorrectly matched If...End If structure inside the outer If...End If structure.

Also check that the block If is correctly formatted.


Else without If

An Else statement is used without a corresponding If statement.  Check other control structures within the If...Else structure and verify that they are correctly matched.  For example, a While without a matching Wend inside the If...Else structure will generate this error.

Also check that the block If is correctly formatted.


Exit Do not within Do...Loop

An Exit Do statement is used outside of a Do...Loop statement.  Make sure a valid Do statement precedes the Exit Do.


Exit For not within For...Next

An Exit For statement is used outside of a For...Next statement.  Make sure a valid For statement precedes the Exit For.


Loop without Do

A Loop statement is used without a corresponding Do statement.  Check other control structures within the Do...Loop structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Do...Loop structure will generate this error.


Select Case without End Select

A Select statement is used without a corresponding End Select statement.  Check if there is an incorrectly matched Select...End Select structure inside the outer Select...End Select structure.  If you have nested Select Case statements, each must have a matching End Select.


Case without Select Case

A Case statement is used without a corresponding Select Case statement.  Check other control structures within the Select Case...Case structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Select Case...Case structure will generate this error.


End Select without Select Case

An End Select statement is used without a corresponding Select Case statement.  Check other control structures within the Select Case...End Select structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Select Case...End Select structure will generate this error.


User-defined type variable not allowed in expression

A variable of a user-defined type must be passed by reference in a Sub or Function call [image] it cannot be passed by value (i.e., as an expression).  For example, Sub1 Record is allowed, but Sub1 (Record) produces this error.  Note that you can pass an element of a user-defined type by value.  For example, Sub1 (Record.Element1) is allowed if Element1 is an fundamental data type -- that is, Integer, Long, Single, Double, Currency, String or Variant.


Parameter type mismatch

Possible causes:

An argument in a Sub or Function call does not have the correct data type.  For example, trying to pass a numeric value where a string is expected or vice versa produces this error.

An argument in a Sub or Function call is a property and is passed by reference [image] properties must be passed by value.  To pass an argument by value, either use ByVal in the Sub or Function argument list definition or enclose the argument in parentheses in the Sub or Function call.  For example, to pass the command button Caption property to a procedure,  Sub1 (Command1.Caption) is allowed, but  Sub1 Command1.Caption  produces this error.


Statements/labels invalid between Select Case and Case

Statements and line labels or line numbers are not permitted between Select Case and the first Case statement.  Comments and statement separators are permitted.


Invalid outside of Type block

The element As type clause is permitted only within a Type...End Type block.


Expression not allowed here

The indexes in an array definition, such as in a Dim, Global, or Static statement, cannot contain an expression.  For example,  Dim x(3*5)  will produce this error.  You can use a Const statement to evaluate the expression and then use the constant to dimension the array.


Duplicate Deftype statement

Part or all of the letter range for this Deftype statement is already included in another Deftype statement at this level of scope.


Label not defined

A line label or line number is referred to (in a Goto statement, for example), but does not occur in the code.


For without Next

A For statement is used without a corresponding Next statement.  Check if there is an incorrectly matched For...Next structure inside the outer For...Next structure.


While without Wend

A While statement is used without a corresponding Wend statement.  Check if there is an incorrectly matched While...Wend structure inside the outer While...Wend structure.


Wend without While

A Wend statement is used without a corresponding While statement.  Check other control structures within the While...Wend structure and verify that they are correctly matched.  For example, an If without a matching End If inside the While...Wend structure will generate this error.


Array not defined

Visual Basic requires all arrays to be declared [image]. You declare an array with a Dim, Global, Static, or ReDim statement.


Variable required

Possible causes:

You have attempted to use a numeric expression as an argument to the Len function.  The Len function does not accept a numeric expression, but it does accept either a string or numeric variable or a string expression.

You have used a function call  or an expression as an argument to Input, Let, Get, or Put.  For example, you've used an argument that appears to be a valid reference to an array variable, but instead is a call to a function of the same name.  These statements do not accept function calls as arguments.


This variable can't be passed by value
This variable type can't be passed by value

Object variables must be passed by reference.  For example, if the argument of a procedure named Sub1 is defined to be of the control data type, that is, Sub1 (A as Control), then  Sub1 Command1  is allowed, but Sub1 (Command1) is not.  Putting parentheses around an argument causes it to be passed by value.


Function reference must be followed by ( )

A Visual Basic Function procedure is called using the function name, followed by the argument list in parentheses.  If the function has no arguments, you still must include the parentheses unless a Declare statement was used to declare the function.


Next without For

A Next statement is used without a corresponding For statement.  Check other control structures within the For...Next structure and verify that they are correctly matched.  For example, an If without a matching End If inside the For...Next structure will generate this error.


Invalid use of object

Get, Input #, Line Input #, LSet, Mid$, Put, and RSet cannot be used with objects or properties.  For example,  Input #1, Form1.BackColor  will produce this message.


Invalid argument for DLL Sub or Function

You can pass array elements, but not a whole array, to a DLL.


Function not defined

A statement in the code looks like a function call, but there is no corresponding function definition with that name.

Possible causes:

The function name is misspelled or is not defined.

The scope of the function does not extend to the procedure that is referring to it.  Note that code within a form is recognized only by the procedures in that form.


Reference to undefined function or array

A statement in the code looks like a function call or array, but there is no corresponding function definition with that name.

Possible causes:

The function or array name is misspelled or is not defined.

The scope of the function or array does not extend to the procedure that is referring to it.  Note that code within a form is recognized only by the procedures in that form.


Duplicate definition with existing object

There is already an object with this name.


ReDim not allowed on object

You cannot resize a object array using Redim.  Use the Load statement to add more controls to a control array.  Use Unload to remove controls from a control array.


User-defined type with Variant or variable-length String element not allowed.

LSet or RSet require that user-defined datatypes have fixed-length data elements.


Must have startup form or Sub Main ()

There is no form in the current project, and the current project does not have a Sub procedure named "Main" in any module.  You must have one or the other to run a Visual Basic application.


Can't save file to TEMP

The directory established by your TEMP environment variable cannot be written to.  Check that your TEMP environment variable is set to a valid directory and that the disk is not full.


Error reading Tutorial file 'item'

The Tutorial file is damaged.  To reinstall the Tutorial, use the Visual Basic Setup disks.


Tutorial directory 'item' not found

The Tutorial directory, VB.CBT, was not found.  To install the Tutorial, use the Visual Basic Setup disks.


Can't find Tutorial file 'item'
Can't find file 'item'

A file needed by the Tutorial or Intro Computer Based Training (CBT) cannot be found. The tutorial file should be in the VB.CBT directory.  The Intro file should be in the Visual Basic (VB) directory  To reinstall the Tutorial or Intro files, use the Visual Basic Setup disks.


Not enough memory to load Tutorial
Not enough memory to load help file.

The Tutorial or Intro help files cannot be loaded because of low memory.  Close some documents or applications that are not needed and try again.


One or more replacements too long and not made

A Replace operation has attempted to create a line of code longer than the 1023-character maximum allowed.  Those replacements where the resulting line is less than 1023 characters were completed.  Use the Find command to find instances where the replacement was not done and break the long statements into several lines.


Syntax errors produced while replacing

The Replace command has introduced some errors in the code.


Can't find Windows Help .EXE file

The Windows Help application is not available.  If WINHELP.EXE is on your machine, make sure it is on your path.  If it is not on your machine, run Windows Setup to install it.


Invalid procedure name

A procedure name cannot be a reserved word, must start with a letter, and can be a maximum of 40 characters [image] including letters, numbers, and underscores (_).  Function procedure names can include a type declaration character, but Sub procedure names cannot.


Nothing to search for or replace

Find doesn't have anything to look for.  Enter a string into the Find What text box from the Find or Replace dialog box on the Code menu.


Not enough room to paste contents into current line

A line of Visual Basic code cannot contain more than 1023 characters.  Break the line into individual statements or assign some expressions to intermediate variables.


Can't set next statement

You are trying to set the next statement to a statement outside the current procedure.  The Set Next Statement command on the Run menu works only within the current procedure.


Search text not found

The specified text was not found during the search.  You might expand the search to "Current module" or "All modules" by checking the appropriate box in the Search dialog box.


Array already has a control at index 'item'

Possible causes:

You tried to change the index to a number that is already used by this control array.  To determine which indexes have already been assigned, select the Index property on the Properties bar for each control array element.  The assigned index appears in the Settings text box.

You tried to change the CtlName of a control in an array to the name of a control array already using this index.


Not a legal object name: 'item'

Form and control names must start with a letter and can be a maximum of 40 characters [image] including letters, numbers, and underscores (_).

Note that FormName and CtlName properties are different from the label properties [image] Caption, Text, and Value [image] which label or display the contents of a control at run time.  These properties can be reserved words, can begin with a number, and can contain non-alphanumeric characters.


Must specify which item(s) to print

You have not specified what to print.  Check at least one of the Form or Code check boxes in the Print dialog box after choosing Print from the File menu.


'item' is a form property name

You can't use the name of a form property to name a control.  To find out what words are reserved for form property names, see the Form topic in Help for complete information.


'item' is a form name

A form already has this name.  To find the duplicate, look in the Project window at the list of forms used in the project.  Note that a control cannot have the same name as any form in the same project.


'item' is a system object name

Screen, Clipboard, and Printer name system objects, so they cannot be used as a form or control name.


Event handler must be a Sub procedure

A valid event procedure, such as Form_Click, must be a Sub procedure [image] it cannot be a Function procedure.


Incorrect number of event procedure arguments

Possible causes:

An event procedure for a control array needs to be defined with the Index argument [image] for example, Command1_Click (Index as Integer), while an event procedure for a non-control array cannot take the Index argument.  Check the control's Index property.  If it is non-null then the control is considered part of a control array.

An event procedure was written for a control before the control was made part of a control array or before the control was removed from a control array.  In either case, the number of arguments is incorrect, either because the index needs to be added or because it must be removed.  Edit the event procedure in the Code window to add or remove the index argument.

An argument has been added or removed from the event procedure definition.  You can determine the correct syntax of the event procedure by looking at Help on the event.


Event procedure argument has incorrect data type

Some change has been made to the data type of an event procedure's arguments  The data type does not match the data type specified in the original event procedure definition.  To determine what the argument data types should be, use Search in Help to find the event procedure name and change the arguments back to what they originally were.


Can't assign shortcut key to menu name

You are trying to assign a key combination to a parent or top-level menu item that is not a command.  Only commands can have shortcut keys assigned to them.


Can't use separator bar as menu name

You are trying to put a separator bar in a parent or top-level menu name [image] these names must be text.


Shortcut key already assigned

You tried to assign an shortcut key that has already been assigned to another menu item.  Reassign the shortcut key.


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

You are trying to modify a separator on a menu.  Separators help to visually organize menu items.  They can't be disabled or enabled, or modified with check marks or shortcut keys.


At least one submenu item must be visible

The Visible property can't be set to False (0) for the last visible submenu item.  You can't have a parent menu with no visible submenu items.


Can't load Custom Control DLL: 'item'

Visual Basic could not load the specified custom control dynamic-link library (DLL).

Possible causes:

You attempted to use the Add File command to load a DLL file that is not a valid Visual Basic custom control DLL.  Custom control files usually have a .VBX extension.

You opened a project that contained a reference to a custom control DLL.  This DLL file exists but is not a valid custom control DLL.  The DLL file may have been damaged in some way; try replacing it with an undamaged copy.


Can't unload Custom Control DLL; in use

You can't remove a custom control dynamic-link library (.VBX) file from the project when a custom control from that file has been placed on a form.  If you want to unload the custom control file, first remove all of that file's custom controls from all forms in the project.


Can't quit at this time

You can't quit Windows while Visual Basic is in run or break mode.  You also can't quit Windows while a dialog box or message box is displayed.


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

You have edited some code that invalidates the current state of your program and requires reinitializing the program.  Click Cancel to restore the code to its original state, or click OK to re-initialize your program.


Invalid command-line argument 'item'

There is an invalid argument in the command line used to invoke Visual Basic.  Valid command line arguments are:

/run  ProjectName

FileName

/cmd  command-line argument


Reset halted programs so Code window can be closed?

To close the Code window and reinitialize your program, click OK.  To continue running your program, click Cancel.


Save changes to 'item'?

This file has changed since it was last saved.  Click Yes to save it, click No to close the file without saving it, or click Cancel if you do not want to close the file.


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

There is not enough stack space to save the current state and enter break mode.  To continue running the program, choose OK.  To reinitialize your program and return to design mode, choose Cancel.


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

There is not enough stack space to save the current state and enter break mode.  You must restart or end the program.


Line too long to edit--edit truncated line?

The current line is longer than the Visual Basic code editor can handle.  After you enter a line of code in the Code window, extra spaces are added between items in the line, which may make the line longer than the 1023-character maximum.  The line will still be readable by Visual Basic, but cannot be edited without losing some characters from the end of the line.

If you need to save this line, use the Save Text command on the File menu to save it to a file, and then use a different editor to break the line into separate lines or to assign some expressions to intermediate variables.  Reload the file into Visual Basic with the Load Text command on the File menu.


'item' has been changed; must reset

The changes you made require you to restart the program.


Search complete

There are no more instances of the text you want to search for.  If all instances were not found, verify the options you chose in the Find or Replace dialog box.


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

You've tried to set CtlName or paste a new control onto the form, and you already have a control with the indicated name.

If you would like to create a control array, choose Yes.  The newly created control array element will have an Index one higher than the control previously created with this name.  If you do not want to create a control array, choose No.  If you're pasting a control, Visual Basic will generate a name for the new control.


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

You may have tried to load a form with controls whose names conflict with forms already in the project.  For example, loading Form2 that contains a Form1 control will trigger this error.


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

This error message appears after another error has occurred.  Once you've taken the appropriate action for that error, you will see this error message.  To load the control anyway, choose Yes; to cancel the loading, choose No.


Form had old file format

The form or module has an old file format.  To update the file format, choose Save File or Save Project from the File menu.


Replace existing 'item'?

There is already a file by that name.  Click Yes to replace that file with the current file, or click Cancel to stop the save operation.


'item' does not exist

The file you specified does not exist in the specified directory.  Check that you have spelled the file name correctly and specified the correct directory.


'item' already exists in project

The file you specified is already part of the project.  You cannot add the same file to a project more than once.  You cannot save a file with the same name as another file in the project.


Parent or top level menu item may not be checked
Parent or top-level menu item may not be checked

You may not use the checked option on the menu item that will appear on the menu bar or on a menu that has submenus.


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

Visual Basic could not load the code in this form file. Do you want to continue to load the form anyway?


Search string too long.
Search string too long

The length of the string that you are searching for is too long. Reduce the length of the string and try again.


Unable to get system fixed font

A request was made for the system fixed font.  The font returned was not fixed-pitch.  There may be a problem with the font or screen driver setup on your system.  You may need to reinstall Microsoft Windows.


Incompatible version created '|'
Incompatible version created '<filename>'

The binary program file being loaded was incompatible with the current version of Visual Basic.  This can occur when the binary file is damaged or created by a version not supported by the current version.


Return without GoSub

Error 3

A Return statement doesn't have a corresponding GoSub statement.

Unlike For...Next, While...Wend, and Sub...End Sub, which are matched at compile time, GoSub and Return are matched at run time.


Illegal function call

Error 5

Possible causes:

A statement or function has an improper or out-of-range argument.  For example:

A negative or unreasonably large subscript

A negative number raised to a non-integer power

A negative record number in a Get or Put statement

An I/O function or statement (Loc or LOF, for example) performed on a device that does not support it

Strings are concatenated to create a string greater than 65,535 characters in length

Invalid method call, such as an inappropriate method argument


Overflow

Error 6

Possible causes:

The result of an assignment, calculation, or data type conversion is too large to be represented within the range allowed for that type of variable.

An assignment to a property exceeds the maximum value the property can accept.  The assignment may not necessarily be one that you have made in your code.  Some methods make automatic assignments to properties.  For example, in the course of execution, the Print method changes CurrentX and CurrentY properties.  Any attempt to print at an invalid CurrentX or CurrentY location results in an Overflow error.


Out of memory

Error 7

More memory was required than is available, or a 64K segment boundary was hit.  To prevent this error, you should try the following:

Close any unneeded applications, documents, or source files that are in memory.

If you have extremely large modules or procedures, consider breaking them into smaller ones.  This doesn't save memory, but it can prevent hitting 64K segment boundaries.

If you are running Windows in standard mode on a 386 or 486 computer, try enhanced mode.

If you are running Windows in enhanced mode, free up some disk space, or least ensure that some space is available.

Eliminate terminate-and-stay-resident programs.

Eliminate unneeded device drivers.

Reduce the number of global variables.


Subscript out of range

Error 9

Possible causes:

Reference to a nonexistent array element.  The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application.


Duplicate definition

Error 10

The specified name is already used at this level of scope.  You can use the Find command on the File menu to help locate the duplicate name.  When specifying the name to search for,  remove the type-declaration character, if there is one, since a conflict occurs if the names are the same and the type-declaration characters are different.

Possible causes:

A new variable or procedure has the same name as an existing variable or procedure.

A Const statement uses the same name as an existing variable or procedure.

You declared a fixed array more than once.

You tried to use Dim or ReDim to declare the dimensions of an already-dimensioned dynamic array without first using Erase to deallocate the array.


Division by zero

Error 11

This error is caused by dividing by zero in an expression.


Type mismatch

Error 13

Possible causes:

The variable or property is not of the correct type.  For example, a variable that requires an integer value cannot accept a string value.

An If TypeOf statement was used with something other than a control.

An object that is not a form has been passed to a procedure that is expecting a form as an argument.

An object that is not a control has been passed to a procedure that is expecting a control as an argument.


Out of string space

Error 14

Possible causes:

You tried to create a single string array larger than 64K.

You may have run out of memory, which has prevented a 64K string space from being allocated.


String formula too complex

Error 16

A string expression is too complicated.  Strings not assigned to variables (such as those returned by functions) are assigned to temporary locations during string expression evaluation.  Having a large number of such strings can cause this error.  Try assigning these strings to variables and use the variables in the expression instead.


Can't continue

Error 17

You have made a change to the code that prevents execution from continuing.  Choose Continue or End from the Run menu.


No Resume

Error 19

The program has encountered the end of the program while executing an error-handling routine.  Add a Resume statement to the error-handling routine.  If you want to exit the error-handling routine without resuming, use an Exit statement.


Resume without error

Error 20

A Resume statement has been encountered, but there is no active error-handling routine because there is no On Error statement.


Out of stack space

Error 28

Possible Causes:

Too many active Function or Sub calls.  Check that both event and general recursive procedures are not nested too deeply and that they terminate properly.

A cascading events will cause this error.

Local variables require more local variable space than is available.  Try declaring some variables at the module level instead.  You can also use the Static keyword with Sub or Function to declare the entire procedure, in which case all local variables will be static. Or you can use the Static statement to declare static variables within individual procedures

Fixed-length strings use more stack space than variable-length strings.  Try redefining some of your fixed-length strings as variable-length strings.

Too many nested DoEvents statements.

Use the "Calls" menu to view which procedures are active (on the stack).


Sub or Function not defined

Error 35

A Sub or Function procedure is called but is not defined.

Possible causes:

The specified procedure is not visible to the calling procedure.  Procedures in a form cannot be called from procedures outside the form.   Use Find on the Edit menu to locate the procedure.

You have declared a dynamic-link library routine, but the routine is not in the specified library.

You have misspelled the name of your procedure.


Error in loading DLL

Error 48

The specified DLL cannot be loaded.  This is usually because the file specified with the Lib clause in the Declare statement is not a valid DLL.

Possible causes:

The file is not DLL-executable.

The file is not a Windows DLL.

The file is an old Windows DLL that is incompatible with Windows protect mode.

The DLL requests another DLL that is not present.


Bad DLL calling convention

Error 49

Your program is calling a routine in a dynamic-link library that either is being passed the wrong type or number of arguments or does not use the Pascal calling convention.  Make sure that the arguments passed to the DLL routine exactly match the arguments expected by the routine.  If the DLL routine expects arguments by value, then make sure ByVal is specified for those arguments in the declaration for the routine.


Internal error

Error 51

An internal malfunction has occurred in Visual Basic.  Unless this call was generated by the Error statement, use the Product Assistance Request form included with your documentation to report to Microsoft the conditions under which the message appeared.


Bad file name or number

Error 52

A statement or command refers to a file with a file number or file name that is not specified in the Open statement or is out of the range of file numbers specified earlier in the application.

The filename used may be invalid. When using MS DOS, you will need to use the following conventions for naming files and directories.

The name of a file or directory can have two parts: a name and an optional extension. The two parts are separated by a period (for example, MYFILE.NEW).

The name can contain up to eight characters, and the extension can contain up to three characters.

The name must start with either a letter or number. It can contain any uppercase or lowercase (filenames are not case-sensitive) characters except the following:

period (.)	quotation mark (")
slash (/)	backslash (\)
brackets ([ ])	colon (:)
semicolon (;)	vertical bar (|)
equal sign (=)	comma (,)

The name should not contain any spaces. The following names are reserved and cannot be used for files or directories: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL.  Examples of valid filenames are LETTER.DOC, MEMO.TXT, BUDGET.92, 12345678.901 and 2NDTRY.RPT.


File not found

Error 53

Possible causes:

A Kill, Name, or Open statement refers to a file that does not exist.

An attempt has been made to call a procedure in a DLL and the library file name specified in the Lib clause of the Declare statement cannot be found.


Bad file mode

Error 54

Possible causes:

A Put or Get statement specifies a sequential file. Put or Get can only refer to files opened as Random.

A Print # statement specifies a file mode other than Output or Append.

An Input # statement specifies a file mode other than Input.


File already open

Error 55

Possible causes:

A sequential-output-mode Open statement was executed for a file that is already open.

A Kill, SetAttr, or Name statement refers to an open file.


Device I/O error

Error 57

An input or output error occurred while your program was using a device such as the printer or disk drive.


File already exists

Error 58

The new file name specified in a Name statement is identical to a file name that already exists.


Bad record length

Error 59

The length of a record variable for a Get or Put statement does not match the length specified in the corresponding Open statement.  Because a two-byte descriptor is always added to a variable-length string Put to a random access file, the variable-length string must be at least two characters shorter than the record length specified in the Len clause of the Open statement. Variant data types also require a two-byte descriptor.  Variants containing variable-length strings require a four-byte descriptor.


Disk full

Error 61

Possible causes:

There isn't enough room on the disk for the completion of a Print #, Write #, or Close operation.

There isn't enough room on the disk for Visual Basic to create files it requires for successful operation.

Move some files to another disk, or delete some files.


Input past end of file

Error 62

An Input # or Line Input# statement is reading from an empty file, or from a file in which all data has already been read.  To avoid this error, use the EOF function to detect the end-of-file just before the Input # statement.


Bad record number

Error 63

The record number in a Put or Get statement is less than or equal to zero.


Bad file name

Error 64

A file name does not follow DOS naming conventions.


Too many files

Error 67

Possible causes:

There is a limit to the number of disk files that can be open at one time.  This limit is a function of the "Files=" setting in your CONFIG.SYS file.  Increase that number and reboot.

The operating system has a limit to the number of files in the root directory (usually 512).  If your program is opening, closing, and/or saving files in the root directory, change your program so it uses a subdirectory.


Device unavailable

Error 68

The device you are trying to access is not online or does not exist.


Permission denied

Error 70

An attempt was made to write to a write-protected disk or to access a locked file.  For example, this error will occur if an Open For Output statement is performed on a write-protected file.


Disk not ready

Error 71

There is no disk in the drive specified, or the drive door is open.  Insert a disk in the drive, close the door, and retry the operation.


Can't rename with different drive

Error 74

You cannot use the Name statement to rename a file with a new drive designation.  Use FileCopy to write the file to another drive, and delete the old file with a Kill statement.


Path/File access error

Error 75

During an Open, MkDir, ChDir, or RmDir operation, the operating system could not make a connection between the path and the file name.

Make sure the file specification is formatted correctly.  A file name can contain a fully qualified or relative path.  A fully qualified path starts with the drive name (if the path is on another drive) and lists the explicit path from the root to the file.  Any path that is not fully qualified is relative to the current drive and directory.

This error can also occur while attempting to save a file that would replace an existing read-only file.


Path not found

Error 76

During an Open, MkDir, ChDir, or RmDir operation, the operating system was unable to find the specified path.  Make sure the path is typed correctly.


No timer available

Error 260

Possible causes:

There are too many timer controls active.  There is a limit of 16 timer controls in the environment.

There is not enough memory to load a timer control.  Try to free up some memory by closing other applications.


DDE channel not fully closed; awaiting response from foreign application

Error 280

Your Visual Basic application has terminated one DDE conversation with another application and has attempted to start a new conversation, but the other application has not finished handling the termination of the first conversation.

Possible causes:

The other application is waiting for a response from the user.  Switch to that application and take an action appropriate to the message it is displaying.

Your code is not yielding to allow other applications to handle events.  Call the DoEvents function and try establishing the link again.


No more DDE channels

Error 281

Too many DDE conversations are active at the same time.  Terminate some existing DDE conversations by setting LinkMode to 0 (None) before attempting to establish new conversations.


No foreign application responded to a DDE initiate

Error 282

Visual Basic could not find an application and topic corresponding to the application name and topic in the LinkTopic property.

Possible causes:

The application specified in LinkTopic is not running.

The application is running, but doesn't recognize the topic of the link.


Multiple applications responded to a DDE initiate

Error 283

At least two running applications have responded to the application name and topic you specified in the LinkTopic property.  This can happen if several instances of the same application are running and you attempt to initiate a DDE conversation on a topic more than one of them recognize.  To establish a DDE conversation, the combination of application and topic must be unique.


DDE channel locked

Error 284

You have attempted to initiate a new DDE conversation or perform a DDE method on a DDE link that another application has not freed.  Try calling the DoEvents function before setting LinkTopic to Automatic (1) or Manual (2) or before performing a LinkExecute, LinkPoke, LinkRequest, or LinkSend method.


Foreign application won't perform DDE method or operation

Error 285

An application refused to perform the DDE method or operation you attempted.

Possible causes:

You supplied data or commands that the other application did not recognize.  Check the application's documentation to see what data or commands it recognizes.

The LinkItem property is not set to an item that the other application recognizes as valid for the topic of the conversation.  Check the application's documentation to see what items it recognizes.


Timeout occured while waiting for DDE response
Timeout occurred while waiting for DDE response

Error 286

The other application in a DDE conversation did not respond in the time specified by the LinkTimeout property.

Possible causes:

The other application is not responding because it is waiting for a response from the user.  Switch to that application and close the dialog box or take an action appropriate to the message it is displaying.

The LinkTimeout property is set to a value that is too low.  Try increasing the value.

The other application is too busy to respond to DDE messages.  Try calling the DoEvents function before performing this DDE operation.


User pressed ALT key during DDE operation

Error 287

You pressed the ALT key while waiting for a DDE operation to be completed.  If DDE operations are taking too long, try setting the LinkTimeout property to a lower value.


Destination is busy

Error 288

The other application in the DDE conversation is busy and cannot perform a DDE operation.  Try calling DoEvents and attempt the DDE operation again.


Data not provided in DDE operation

Error 289

Visual Basic has encountered an unexpected error while attempting to perform a DDE operation.  The other application informed Visual Basic it was supplying data in a DDE conversation but did not provide it when requested.  The other application may not be performing DDE correctly.


Data in wrong format

Error 290

An application in a DDE conversation supplied data in an unexpected format.  It may not be performing DDE correctly.

Possible causes:

The application is supplying data in a format that Visual Basic does not recognize.  Try initiating the conversation with a different topic.

The application is supplying text data to a picture box or picture data to a text box.  Try initiating the conversation with a different control.


Foreign application quit

Error 291

The other application in a DDE conversation quit unexpectedly.  A DDE operation can't take place unless the other application is running.


DDE conversation closed or changed

Error 292

The other application has closed or changed the DDE conversation unexpectedly.  Terminate this conversation and attempt to establish a new conversation with the application.


DDE method invoked with no channel open

Error 293

A DDE method (LinkExecute, LinkPoke, LinkRequest, or LinkSend) was performed on a control that is not involved in a valid DDE conversation.

Possible causes:

Changing the LinkTopic property terminates an existing DDE conversation but does not automatically establish a new conversation.  After changing the LinkTopic property for a control, you must set the LinkMode property to 1 (Automatic) or 2 (Manual) before executing a DDE method on this control.

You executed a DDE method on a control with LinkMode set to 0 (None).  Set the LinkMode to 1 (Automatic) or 2 (Manual) and try again.


Invalid DDE link format

Error 294

The other application in a DDE conversation passed data in CF_LINK format, but it is not valid link data.


Message queue filled; DDE message lost

Error 295

Visual Basic cannot keep up with the number of DDE operations attempted.

Possible causes:

Too many DDE conversations.  Try terminating some DDE conversations.

Too much code in event procedures is executing because of incoming DDE data.  Reduce the amount of code being called as a result of DDE changes, or try calling the DoEvents function.


PasteLink already performed on this control

Error 296

You have already performed a Paste Link on this control.  To paste a new link, first set the LinkMode property of this control to 0 (None), and then use the Paste Link command.


Can't set LinkMode; invalid LinkTopic

Error 297

You've tried to set the LinkMode property but can't because no valid LinkTopic property has been specified.


DDE requires DDEML.DLL

Error 298

A DDE operation was initiated, but the DDEML.DLL file was not located. This file must be present in the path in order for DDE operations to work.


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

Error 320

From within Visual Basic, you cannot give a file the same name as a character device driver, such as AUX, CON, COM1, COM2, LPT1, LPT2, LPT3, LPT4, or NUL.


Invalid file format

Error 321

The form file is damaged.  Try replacing it with an undamaged copy. This could be caused by having mismatched custom controls.  This error could be triggered if the number of properties in the current version of the control do not match the number expected.


Control array element 'item' does not exist

Error 340

You used an index value that does not correspond to an existing element in this control array.  Adjust the value or Load a control into the array with an index equal to the value.


Invalid object array index

Error 341

The index for an object array element cannot be greater than 32,767 or less than 0.


Not enough room to allocate control array 'item'

Error 342

There isn't enough memory to create all the elements of a control array.  If a control array has discontiguous indexes, such as 0, 2, and 4, Visual Basic will use more memory than if the indexes were contiguous (0, 1, 2).  Check either how you've assigned indexes at design time or how your program assigns indexes as it creates new control array elements, and make them contiguous.


Object not an array

Error 343

A control that is not part of any array is referred to as if it has an index, for example, Command1(3).Caption and Command1.Text.  You can refer to an object as an array element only if it is defined to be part of an control array [image] see Creating a Control Array.


Must specify index for object array

Error 344

The control referred to is part of a control array.  Refer to it using CtlName(index).  If you created the control at design time, you can determine the index of the control by selecting it and viewing its Index property in the Properties window.


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

Error 345

No more than 255 controls are allowed on each form.  The total of all menu items and controls on your form would exceed 255 if any more were added.


Object already loaded

Error 360

The control in the control array has already been loaded.  If it was loaded during run time, it can be removed with the Unload statement.


Can't load or unload this object

Error 361

Possible causes:

You've attempted to Load or Unload a system object [image] Screen, Printer, or Clipboard.

You've attempted to Load or Unload a control that is not an element of an existing control array.  For example,  Load CtlArray  will produce this error, while  Load CtlArray(3)  will not.  If a control is already loaded, you can make it visible with the Visible property.


Can't unload controls created at design time

Error 362

Only control array elements loaded at run time can be unloaded.  If a control is created at design time, it cannot later be unloaded, even if it is part of a control array.  However, you can hide any control by setting the Visible property to False.


Custom control 'item' not found

Error 363

The form being loaded contains a custom control that is not part of the current project.  Use the Add File command on the File menu to add the custom control to the project.


Object was unloaded

Error 364

A form was unloaded from its own Form_Load procedure.  The form that was unloaded may have been implicitly loaded.  For example, the following will implicitly load Form2 if it is not already loaded:

Form2.BackColor = Form1.BackColor


Unable to unload within this context

Error 365

In some situations you are not allowed to unload a form or a control on a form.  For example, this occurs when trying to unload a form or control on the form:

During any Paint event for the form or for any control on the form.

Whenever a combo box is pulled down on the form being unloaded or containing the control being unloaded.


No MDI form available to load

Error 366

You set the MDIChild property on a form to True, but at run time, there was no MDI form in your project to load.


Invalid property value

Error 380

An inappropriate value is assigned to a property.  To find out what values are valid for a property, see the remarks in the property's Help topic.


Invalid property array index

Error 381

You tried to use an inappropriate property array index value.  List Property and Fonts Property index values must be greater than 0 and less than 32,767.  For example, List1.List(3) is valid.


'item' property cannot be set at run time
'item' property can't be set at run time

Error 382

The following properties can't be set at run time:

ActiveControl	ActiveForm

BorderStyle (for form and text box only)	ControlBox

Fonts	FontCount

hDC	hWnd

Image	Index

List	ListCount

MaxButton	MinButton

MultiLine	Name

Parent	ScrollBars

Sorted	Style

Text (for list box and combo box only)	Width (for Screen only)


'item' property is read-only

Error 383

The following properties are read-only at both design time and run time.

Property	On Object

hDC	Form, picture box, Printer

Height	Combo box (with Style = 1), drive, Printer

hWnd	Form

Image	Form, picture box

List	Dir, drive, file

ListCount	Combo box, dir, drive, file, list box

Page	Printer

Parent	Any control

Text	Combo box (with Style = 2), list box

Width	Printer


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

Error 384

The Left, Top, and Height, Width properties cannot be changed on a minimized or maximized form.  You can set or return the state of a form with the WindowState Property.  You can prevent a user from maximizing or minimizing a form by setting the MaxButton or MinButton form properties to False (0).


Must specify index when using property array

Error 385

You must specify an index when using the List Property or the Fonts Property.  Index values must be greater than 0 and less than 32,767.  For example, List1.List is invalid because no index is specified.  However, List1.List(3) is valid.


'item' property not available at run time

Error 386

The Name property is not available at run time.


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

Error 387

Possible causes:

The Checked box for a menu control can't be selected when that control is a parent or top-level menu.

The separator bar on a menu control can't be set when the control is a parent or top-level menu item.

The Visible property can't be set to False (0) for the last visible submenu on a parent menu.  You can't have a parent menu with no visible submenu items.


Can't set Visible property from a parent menu

Error 388

The Visible property of a submenu item cannot be set from its parent's menu code.


Name not available.
Name not available

Error 391

A custom control (.VBX) file tried to use the VBGetControlName API against a VISUAL BASIC application in .EXE form. VISUAL BASIC does not embed object names in the executable (.EXE) file. Consult the author of the .VBX file.


MDI Child forms cannot be hidden

Error 392

You cannot set the hidden property to True or use the Hide method with MDI child forms.


'item' property cannot be read at run time

Error 393

You have tried to read a property that is only available in design mode.  Some properties may be visible and alterable at design time but cannot be read during run time.


'item' property is write-only

Error 394

Indicates that a property cannot be read, i.e., "ctl.property = 3" is legal, but "Print ctl.property" generates this error.


Can't use separator bar as menu name

Error 395

A menu caption that has submenus cannot be changed to a separator bar at run time.


Form already displayed; can't show modally

Error 400

You cannot use the Show method to display a modal form if the form is already visible.  Either Unload or Hide the form before attempting to show it as a modal form.  Don't try to display it as a modal form.


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

Error 401

You cannot show a non-modal form when a modal form is displayed.  Unload or Hide the modal form before attempting to use the Show method on another form.


Must close or hide topmost modal form first

Error 402

The modal form you are trying to close or hide is not on top [image] you need to Unload or Hide all modal forms that are on top of this one before you can continue.  A modal form is a form displayed by the Show method with the style% argument equal to 1.


MDI forms cannot be shown modally

Error 403

You may not set the modal option on MDI forms. (MDIForm.Show 1 is incorrect.)


MDI child forms cannot be shown modally.
MDI child forms cannot be shown modally

Error 404

You may not set the modal option on MDI child forms. (MDIChildForm.Show 1 is incorrect.)


Invalid object reference

Error 420

The object that is referred to is not loaded.


Method not applicable for this object

Error 421

Object.method is referred to, but the method is not appropriate for the object.  For example,  Command1.AddItem produces this error because the AddItem method is used only with a list box or combo box.


Property 'item' not found

Error 422

Control.property or Control(index).property is referred to, but property is not defined for this control or you may have misspelled the name of the property.  To see what properties are defined for this control, search for help on properties, events and objects for complete information on a specific control.


Property or control 'item' not found

Error 423

Form.control or Form.property is referred to, but control or property is not defined for this form, or you may have misspelled the name of the control or property.  To see what properties are defined for a form, search Help for Form for complete information.  To see what controls are on this form, look at the list in the Code window's Object box.


Object required

Error 424

Property.property is referred to [image] you need to specify object.property, where object is either a form or control.


Invalid object use

Error 425

You've attempted an invalid assignment using a form or control.  If you want to assign a value to a property or a property value to a variable, remember to include the property name in the object specification.  For example, Form1.Command1.Caption = "OK" instead of Form1.Command1 = "OK".


Only one MDI form allowed

Error 426

You cannot load a file that contains an MDI form if there is already an MDI form in your project. You must remove the file containing the loaded MDI form before loading another.


Invalid Clipboard format

Error 460

The specified Clipboard format is incompatible with the method being executed.  GetText and SetText can be used only with CF_TEXT or CF_LINK formats.  GetData and SetData can be used only with CF_BITMAP, CF_METAFILEPICT (Windows metafile picture), or CF_DIB (device independent bitmap) formats.

Note

The Clipboard formats, such as CF_TEXT and CF_BITMAP, are global constants that must be set to numerical values found in CONSTANT.TXT.  If you do not initialize these in your code, Visual Basic treats them as variables and initializes them to 0.

See Also

GetFormat


Specified format does not match format of data

Error 461

In a GetData or SetData method, the Clipboard format you specified does not match the actual data.  For example, you might have specified CF_BITMAP for the format, but the data is in the Windows metafile format (CF_METAFILEPICT).  Make sure you specify the correct format for the data.

Note

The Clipboard formats, such as CF_TEXT and CF_BITMAP, are global constants that must be set to numerical values found in CONSTANT.TXT.  If you do not initialize these in your code, Visual Basic treats them as variables and initializes them to 0.

See also

GetFormat


Can't create AutoRedraw image

Error 480

There isn't enough available memory to create a persistent bitmap for automatic redraw of the form or picture.  Make the picture box control or form smaller, or reset the AutoRedraw property and perform your own redraw in the Paint event procedure.


Invalid picture

Error 481

You attempted to assign something to the Picture property of a form or picture box that Visual Basic doesn't recognize as an icon, bitmap, or Windows metafile.


Printer error

Error 482

There is some problem that prevents printing.  Some possible causes are:

You don't have a printer selected from the Windows Control Panel.

Your printer is not online.

Your printer is jammed or out of paper.

You tried to print a form to a printer than can accept only text.


Can't empty Clipboard

Error 520

Another application is using the Clipboard and will not release it to your application.


Can't open Clipboard

Error 521

Another application is using the Clipboard and will not release it to your application.


User defined error
User-defined error

The application has executed the Error n% statement which caused a trappable user-defined error. If the Error statement specifies an error code that is not used by Visual Basic, the message "User-defined error" is displayed.


Out of stack space

Possible Causes:

Too many active Function or Sub calls.  Check that recursive procedures, both event and general, terminate and that they are not nested too deeply.

A cascading event will cause this error.

Local variables (which are stored on the stack) require more local variable space than is available.  Try declaring some variables at the form or module level instead.

User-defined types and fixed-length strings share space with the stack.  Try redefining some of these in other ways that do not use static memory.

Arrays declared in procedures share space with the stack. Declare these arrays in a global module if possible.

Too many nested DoEvents.


Identifier is not an object or user-defined type

Possible causes:

Object.property is referenced, but Object does not exist.  Allowable objects are control names, form names, and project names.  Check that the necessary form is in the project, or check that the name is spelled correctly.

Object.method is referenced, but Object does not exist.  Check that the necessary form or control is loaded.

Form.control is referenced, but Form does not exist.

A variable name cannot contain a period [image] it can contain only letters, numbers, underscores (_), and one type declaration character.


Expression too complex

An expression exceeds certain internal limitations of Visual Basic. Perhaps a numeric expression has too many complicated subexpressions.  Try breaking down the expression by assigning some subexpressions to variables.


Duplicate label

Two program lines have the same number or label.  Each line number or line label in form code or a module must be unique.

Check all the Sub and Function procedure definitions in the form code or module for the duplicate label.

You can use the Find command on the Edit menu to locate the duplicate label.


Conflict between Global variable and global procedure name

The highlighted word is already defined.  To find the other occurrence of the highlighted word, choose Find from the Edit menu and then select All Modules from the Search box.  Before you do the Find, remove the type-declaration character, if there is one, since this error message is produced if the names are the same and the type-declaration characters are different.


Array already dimensioned

Possible causes:

You attempted to change the dimensions of a static array with a ReDim statement [image] only dynamic arrays can be redimensioned.  To define a dynamic array, use a Dim, Global, or Static statement with empty parentheses.

An Option Base statement occurs after dimensions have been set.


Do without Loop

A Do statement is used without a terminating Loop statement.  Check that other control structures within the Do...Loop structure are correctly matched.  For example, a block If without a matching End If inside the Do...Loop structure may produce this error.


DEFType statements must preceed declarations
Deftype statements must precede declarations

Within the Declarations section of a form or module, a Deftype statement must occur on a line before variables are defined.


Sub and Function or variable of the same name

A Sub cannot have the same name as a Function, variable, or constant at the same level of scope.


Argument-count mismatch

A Sub or Function procedure call has an incorrect number of arguments.

Compare the Declare statement for the procedure with the statement calling the Sub or Function or the associated Call statement to make sure the argument list has the same number of items in both cases.

Use the Find command on the Edit menu to locate the Declare statement, or Press SHIFT+F2 to locate the selected procedure definition.


Object must be specified

You specified a method where the target object was not provided. For example if you execute: Print "Hi!" in a global procedure (a non-forms module), the target object (the form) is not available. Form1.Print "Hi!" would be correct (assuming Form1 was visible).


Procedure has the same name as a control

A Sub or Function cannot have the same name as a control.  Use the Find command on the Edit menu to locate the Declare statement or press SHIFT+F2 to locate the selected procedure definition.


File not found: |
File not found: <file name>

The file you referenced could not be found. Make sure you used the correct path name, the file is not marked as hidden, and you have permission to access the file.


File already open: |
File already open: <file name>

You attempted to open a file that is already open. Make sure this (and no other) application has this file open.


Device IO error: |
Device I/O error: <device>

A hardware error has occurred. This may be due to damaged disk media or the I/O device itself.


File already exists: |
File already exists: <file name>

You are trying to create a file that already exists.


Disk full: |
Disk full: <drive>

The disk media you are writing to is full.  Delete some unneeded files or choose another drive to which to write/save.


Bad file name: |
Bad file name: <file name>

The file name used was invalid. When using MS-DOS, you will need to use the following conventions for naming files and directories:

The name of a file or directory can have two parts: a name and an optional extension. The two parts are separated by a period (for example, MYFILE.NEW).

The name can contain up to eight characters, and the extension can contain up to three characters.

The name must start with either a letter or number. It can contain any uppercase or lowercase characters  (file names are not case-sensitive) except the following:

period (.)	quotation mark (")
slash (/)	backslash (\)
brackets ([ ])	colon (:)
semicolon (;)	vertical bar (|)
equal sign (=)	comma (,)

The name should not contain any spaces. The following names are reserved and cannot be used for files or directories: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL.  Examples of valid file names are LETTER.DOC, MEMO.TXT, BUDGET.92, 12345678.901 and 2NDTRY.RPT.


Too many files: |
Too many files: <file name>

You have too many files open. Microsoft Windows and MS-DOS can only open a limited number of files.  To correct this situation, try to close some other files in this or other running applications. If this does not work, you may need to increase the FILES=nn statement in the CONFIG.SYS file (and reboot your system).


Permission denied: |
Permission denied: <file name>

You do not have permission to access this file. This may be due to file attributes or other permission violations. For example, you may have tried to write to or erase a file marked as read-only.


Disk-media error: |
Disk-media error: <device>

A hardware error has occurred. This may be due to damaged disk media or the I/O device itself.


Path access error: |
Path access error: <path name>

The path (which designates the directory location for files) could not be accessed.


Path not found: |
Path not found: <path name>

The path (which designates the directory location for files) could not be found.


Text would be too long.  Edit prevented

The current line is too long to edit.  The maximum length of the line is dependent upon the current state of Visual Basic and of the operating system, but is generally 1023 characters.

When working with long strings, it is usually better to use string variables and concatenation to increase the text incrementally.


Duplicate procedure name

A procedure with this name already exists [image] you can use the Find command on the Edit menu (or SHIFT+F2) to help locate the duplicate procedure.  Before you do this, remove the type-declaration character, if there is one, since a conflict occurs if the names are the same and the type-declaration characters are different.


Control must be same type as rest of array

You attempted to give a control the same name as an existing control array of a different type.  All controls in a control array must be the same type.


Can't clear INDEX property without changing CTLNAME
Can't clear Index property without changing name

This control is part of a control array.  If you want to delete its index, and thus delete it from the control array, you must first rename it with a unique name.


| is a control name
<name> is a control name

A control already has this name.  A form cannot have the same name as a control in the same project.


Menu subitem skipped a level

Menu levels must be contiguous.  Menus can be cascaded to five levels.  An item at level 2 can open a pop-up menu at level 3, and an item at level 3 can open a pop-up menu at level 4.

In the Menu Design window, make sure menu items are indented only one level beyond the previous level.


Menu control must have a name

A menu item has been created without assigning a name to it.  Unlike other controls in Visual Basic, menu controls require you to assign names as the control is created, since Visual Basic does not supply a default name for menu items.


Menu control array element must have an index

An item has been added to a menu control array without assigning an index to the item.  Unlike other control arrays in Visual Basic, menu control arrays require you to assign indices as the item is created, since Visual Basic does not supply a default index for menu control array items.


Menu control array indices must be in order
Menu control array indices must be in ascending order

An index assigned to an item in a menu control array is out of order with the other items.  The indices of a menu control array do not have to be contiguous (e.g.,  they could be 1, 3, and 5), but they must be in ascending order according to their location on the menu.  Get the next available index number before assigning a number to the index.


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

You have tried to add an item to a control array, where the other items in the array are adjacent to the current item.  The indices of the items in a menu control array do not have to be contiguous (i.e.,  2, 3, 4), but they must be in ascending order according to their location on the menu.  The items in a menu control array, however, must be located next to each other within the same menu or pop-up menu.


1000Remote data not accessible. Start application '|'?
Remote data not accessible.  Start application <name>?

No running application recognized the LinkTopic you specified.

Possible causes:

The application you specified in the LinkTopic property is not running.  Choose OK and Visual Basic will attempt to run the application.

The application you specified in the LinkTopic property is running, but it does not recognize the topic you specified.  Choose OK and Visual Basic will attempt to run another instance of the application and have it open the topic you specified.

The application you specified in the LinkTopic property is running, but is ignoring DDE messages.  Consult the documentation for that application to see how to make it perform DDE.  (In Microsoft Excel, for example, you must turn off the "Ignore Remote Requests" option in the Options Workspace dialog box.)

The application or topic you specified in the LinkTopic property is not valid.  Choose Cancel and set the LinkTopic property to a valid application and topic.