WithEvents Keyword

Named Arguments

No

Syntax

Dim|Private|Public WithEvents objVarname As objectType

objVarName

Use: Required

Data Type: String

The name of any object variable that refers to an object that exposes events.

objectType

Use: Required

Data Type: Any object type other than the generic Object

The ProgID of a referenced object.

Description

The WithEvents keyword informs VB that the object being referenced exposes events. When you declare an object variable using WithEvents, an entry for the object variable is placed in the code window's drop-down Object List, and a list of the events available to the object variable is placed in the code window's drop-down Procedures List. You can then write code event handlers for the object variable in the same way that you write other more common event handlers such as Form_Load.

Rules at a Glance

  • An object variable declaration using the WithEvents keyword can be used only in an object module such as a Form or Class module.

  • An object variable declaration using the WithEvents keyword should be placed only in the Declarations section of the object module.

  • Any ActiveX object or class module that exposes events can be used with the WithEvents keyword. WithEvents is valid only when used to declare an object variable.

  • You can't use WithEvents when declaring the generic Object type.

  • Unlike other variable declarations, the As keyword is mandatory.

  • There is no limit to the number of object variables that can refer to the same object using the ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.